第九次作业 接口和接口回调

一 需求分析

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

二 代码

package Nine;
import java.util.Scanner;

 interface Shape{
    double getArea();
}

class Rectangle implements Shape {
    double width;
    double length;
    
    public Rectangle(double width,double length) {
        this.width = width;
        this.length = length;
    }

    @Override
    public double getArea() {
        return width*length;
    }
}

class Square extends Rectangle{
    
    public Square(double width) {
        super(width, width);
    }
    public double getArea() {
        return width* width;
    }
}

class Triangle implements Shape{
    double l1;
    double l2;
    double l3;
    public Triangle(double l1,double l2,double l3) {
        this.l1 = l1;
        this.l2 = l2;
        this.l3 = l3;
    }
    public double getArea() {
        double num = (l1+l2+l3)/2;
        return Math.sqrt(num*(num-l1)*(num-l2)*(num-l3));
    }
}

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 gc;
     Factory(char ch){
         this.gc = ch;
     }
     public Shape getShape(){
         switch(gc){
         case 't':shape=new Triangle(1,2,3);break;
         case 'r':shape=new Rectangle(4,5);break;
         case 's':shape=new Square2(6);break;
         case 'c':shape=new Circle(7);break;
         }
         return shape;
     }
     public char getgc(){
         return gc;
         }
     public void setShape(Shape shape){
         this.shape=shape;
         }
     public void setCh(char ch){
         this.gc=ch;
     }
}

public class Yy {

    public static void main(String[] args) {
        for(int i = 0;i<4;i++) {
            Scanner sc = new Scanner(System.in);
            String str = sc.next();
            char ch = str.charAt(0);
            Factory fa=new Factory(ch);
            Prism pri=new Prism(fa.getShape(),6);
            pri.setShape(fa.getShape());
            double vol=pri.getVolumn();
            System.out.println(vol);
        }
        
    }
}

截图

 

posted @ 2019-10-14 22:33  昵称是个啥~~  阅读(141)  评论(0编辑  收藏  举报