第九次作业
题目: 利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
class juxing implements Shape{//定义矩形类并实现接口,求面积 double chang; double kuan; double mianji; juxing(double chang,double kuan){ this.chang=chang; this.kuan=kuan; } public double getmianji() { return mianji=chang*kuan; } }
class zfx implements Shape{//定义正方形类并实现接口,求面积 double bian; zfx(double bian){ this.bian=bian; } public double getmianji(){ return bian*bian; } }
class sjx implements Shape{//定义三角形类并实现接口,求面积 double a; double b; double c; sjx(double a,double b,double c){ this.a=a; this.b=b; this.c=c; } public double getmianji() { double d= (a+b+c)/2; return Math.sqrt(d*(d-a)*(d-b)*(d-c)); } }
class yuanxing implements Shape{//定义圆形类并实现接口,求面积 double r; yuanxing(double r){ this.r=r; } public double getmianji() { return Math.PI*r*r; } }
class tixing implements Shape{//定义梯形类并实现接口,求面积 double sd; double xd; double gao; tixing(double sd,double xd,double gao){ this.gao=gao; this.sd=sd; this.xd=xd; } public double getmianji() { return (sd+xd)*gao/2; } }
class zhuti{//定义柱体类,创建换底方法和球体积方法 Shape shape; double gao; zhuti(Shape shape,double gao){ this.shape=shape; this.gao=gao; } void huandi(Shape shape) { this.shape=shape; } double tiji() { return shape.getmianji()*gao; } }
interface Shape{//定义接口,接口方法 abstract double getmianji(); }
class gc {//创建工厂类 Shape shape=null; Scanner reader =new Scanner(System.in); public Shape shape(){ char q=reader.next().charAt(0); switch(q){ case 'j': System.out.println("矩形面积");shape = new juxing(5,2); break; case 'z': System.out.println("正方形面积");shape = new zfx(6); break; case 's': System.out.println("三角形面积");shape =new sjx(1,4,2); break; case 'y': System.out.println("圆形面积");shape = new yuanxing(2); break; case 't': System.out.println("梯形面积");shape = new tixing(1,2,5); break; } return shape; } }
//主类
public class zz {private static boolean ture;
public static void main(String[] args) {
// TODO Auto-generated method stub
double gao=2;
gc gc1=new gc();
for(;;){
zhuti zhuti1=new zhuti(gc1.shape(), gao);
System.out.println(zhuti1.tiji());
}
}
}
测试结果: