第九次作业

一题目

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

 二 代码

/**创建接口,并创建求面积的方法*/

package act;

 interface Shape {
     double getArea();

}

/**创建圆形类,计算圆的面积*/

package act;

public class yuan implements Shape {
    double r;
    public yuan(double r){
        this.r=r;
    }
    public double getArea(){
        return Math.PI*r*r;
    }
    

}

/**创建正方形类,求正方形为底的面积*/

package act;

public class ZFX implements Shape{
    double bian;
    ZFX(double bian){
        this.bian=bian;
        }
    public double getArea(){
        return bian*bian;
    }
}

/**创建柱体类,获得柱体体积和换底的方法*/

package act;

public class Zhu  {
    Shape shape;
    double gao;
    public Zhu(Shape shape,double gao){
        this.shape=shape;
        this.gao=gao;
    }
    public double getVolume(){
        return shape.getArea()*gao;
    }
    public void setShape(Shape shape){
        this.shape=shape;
    }

}

/**创建三角形类,求三角形的面积*/

package act;

public class Tri implements Shape {
    double a;
    double b;
    double c;
    Tri(double a,double b,double c){
        this.a=a;
        this.b=b;
        this.c=c;
    }
    public double getArea(){
        double z=(a+b+c)/2;
        return Math.sqrt(z*(z-a)*(z-b)*(z-c));
    }
    }

/**创建梯形类,求以梯形为底的面积*/

package act;

public class Ti implements Shape{
    double a,b,c;
    public Ti(double a,double b,double c){
        this.a=a;
        this.b=b;
        this.c=c;
    }
    public double getArea(){
        return (a+b)*c/2;
    }

}

/**创建矩形类,实现求矩形面积*/

package act;

public class Re implements Shape{
    protected double c,k;
    public Re(double c,double k){
            this.c=c;
            this.k=k;
            }
        public double getArea(){
            return c*k;
        }
        }

/**创建工厂类,实现输入一个相应的字符,输出相应图形的体积*/

package act;
import java.util.*;
import java.io.InputStreamReader;
public class G {
        Shape shape;
        Scanner s=new Scanner(System.in);
        char c=s.next().charAt(0);
        public Shape getShape(){
            switch(c){
            case 's':shape=new Tri(3,4,5);break;
            case 'r':shape=new Re(5,6);break;
            case 't':shape=new Ti(3,4,6);break;
            case 'z':shape=new ZFX(9);break;
            case 'c':shape=new yuan(4);break;
            }
            return shape;
        }
        public char getC(){
            return c;
            }
        public void setShape(Shape shape){
            this.shape=shape;
            }
        public void setC(char c){
            this.c=c;
        }
}

/**在主类中输出以各种其他图形为底的体积*/

package act;

import java.util.*;
public class ZL {
    public static void main(String[] args) {
        for(int j=0;j<5;j++){
        System.out.println("输入的形状为:");
        G m=new G();
        Zhu cone1=new Zhu(m.getShape(),6);
        cone1.setShape(m.getShape());
        double i=cone1.getVolume();
        System.out.println(i);
                }
    }
}

运行结果

原文地址:https://www.cnblogs.com/shuang123/p/11657540.html