接口及接口回调

题目:

       利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。

package Test;

public class test9 {

    public static void main(String[] args) {
        Factory fa=new Factory('s');
        Prism pri=new Prism(fa.getShape(),6);
        pri.setShape(fa.getShape());
        double vol=pri.getVolumn();
        System.out.println(vol);
    }
}
//图形类
interface Shape{
    double getArea();
}
//长方形类
class Rectangle2 implements Shape {
    double width;
    double length;
    
    public Rectangle2(double width,double length) {
        this.width = width;
        this.length = length;
    }

    @Override
    public double getArea() {
        // TODO Auto-generated method stub
        return width*length;
    }
}
//正方形类
class Square2 extends Rectangle2{
    
    public Square2(double lenside) {
        super(lenside, lenside);
        // TODO Auto-generated constructor stub
    }
    public double getArea() {
        return width* length;
    }
}
//三角形类
class Triangle implements Shape{
    double lenside1;
    double lenside2;
    double lenside3;
    public Triangle(double lenside1,double lenside2,double lenside3) {
        this.lenside1 = lenside1;
        this.lenside2 = lenside3;
        this.lenside3 = lenside3;
    }
    @Override
    public double getArea() {
        // TODO Auto-generated method stub
        double count = (lenside1+lenside2+lenside3)/2;
        return Math.sqrt(count*(count-lenside1)*(count-lenside2)*(count-lenside3));
    }
}
//棱柱类
class Prism {
    Shape shape;
    double hight;
    public Prism(Shape shape,double hight) {
        this.hight = hight;
        this.shape = shape;
    }
    public double getVolumn() {
        return shape.getArea()*hight;
    }
    public void setShape(Shape shape) {
        this.shape = shape;
    }
}
//圆类
class Circle implements Shape{
    double r;
    final double PI=3.14;
    Circle(double r){
        this.r=r;
    }
    public double getArea(){
        return PI*r*r;
    }
}
//工厂
class Factory{
     Shape shape;
     char ch;
     //s.next().charAt(0);
     Factory(char ch){
         this.ch = ch;
     }
     public Shape getShape(){
         switch(ch){
         case 't':shape=new Triangle(1,2,3);break;
         case 'r':shape=new Rectangle2(4,5);break;
         case 's':shape=new Square2(6);break;
         case 'c':shape=new Circle(7);break;
         }
         return shape;
     }
     public char getCh(){
         return ch;
         }
     public void setShape(Shape shape){
         this.shape=shape;
         }
     public void setCh(char ch){
         this.ch=ch;
     }
}

posted @ 2019-10-14 14:01  James_Harden  阅读(178)  评论(0编辑  收藏  举报