第九次作业
一、题目:
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
二、代码:
1、工厂类:
1 package gch; 2 3 import java.util.Scanner; 4 5 public class Factory {//工厂类 实现通过输入字符,自动创建对应类型的对象 6 xingzhuang shape=null; 7 Scanner reader = new Scanner(System.in); 8 public xingzhuang getShape() { 9 char i=reader.next().charAt(0); 10 switch(i) { 11 case'y':System.out.println("以圆形为底的柱体体积为:");shape=new yuanlei(5);break; 12 case'z':System.out.println("以正方形为底的柱体体积为:");shape=new zhengfang(5);break; 13 case't':System.out.println("以梯形为底的柱体体积为:");shape=new tixing(2,5,3);break; 14 case'j':System.out.println("以矩形为底的柱体体积为:");shape=new juxing(3,5);break; 15 case's':System.out.println("以三角形为底的柱体体积为:");shape=new sanjiao(2,3,5);break; 16 } 17 return shape; 18 } 19 } 20
2、矩形类:
1 package gch; 2 //定义矩形类和计算方法 3 public class juxing implements xingzhuang{ 4 public double length; 5 public double width; 6 public juxing(double length,double width){ 7 this.length=length; 8 this.width=width; 9 } 10 public double getArea(){ 11 return width*length; 12 } 13 }
3、三角类:
1 package gch; 2 //定义三角类和计算方法 3 public class sanjiao implements xingzhuang{ 4 double a,b,c; 5 public sanjiao(double a,double b,double c){ 6 this.a=a; 7 this.b=b; 8 this.c=c; 9 } 10 public double getArea() { 11 double m=(a+b+c)/2; 12 return Math.sqrt(m*(m-a)*(m-b)*(m-c)); 13 } 14 }
4、主类:
1 package gch; 2 3 import java.util.Scanner; 4 5 public class Test9 { 6 public static void main(String[] args) { 7 System.out.println("请输入柱体的高:"); 8 double h; 9 Scanner r=new Scanner(System.in); 10 h=r.nextDouble(); 11 for(int j=0;j<5;j++){ 12 System.out.println("请选择柱体以那种图形为底:“y”为圆形,“z”为正方形,“t”为梯形,“j”为矩形“s”为三角形"); 13 Factory f=new Factory(); 14 zhulei col=new zhulei(f.getShape(),h); 15 col.changeShape(f.shape); 16 System.out.println(col.getVolumn()); 17 return ; 18 } 19 } 20 }
5、梯形类:
1 package gch; 2 //定义梯形类和计算方法 3 public class tixing implements xingzhuang { 4 double a; 5 double b; 6 double h; 7 public tixing(double a,double b,double h){ 8 this.a=a; 9 this.b=b; 10 this.h=h; 11 } 12 public double getArea(){ 13 return (a+b)*h/2; 14 } 15 }
6、形状接口:
1 package gch; 2 //定义求面积方法的接口 3 public interface xingzhuang { 4 public double getArea(); 5 }
7、圆类:
1 package gch; 2 //定义圆类和计算方法 3 public class yuanlei implements xingzhuang{ 4 double r; 5 public yuanlei(double r){ 6 this.r=r; 7 } 8 public double getArea(){ 9 return 3.14*r*r; 10 } 11 }
8、正方形类:
1 package gch; 2 3 //定义正方形类并继承矩形类 4 public class zhengfang implements xingzhuang{ 5 double a; 6 public zhengfang(double a){ 7 this.a=a; 8 } 9 public double getArea(){ 10 return a*a; 11 } 12 }
9、柱体类:
1 package gch; 2 //定义柱体类,高和换底方法 3 public class zhulei { 4 xingzhuang shape; 5 double height; 6 public zhulei(xingzhuang shape,double height){ 7 this.shape=shape; 8 this.height=height; 9 } 10 public double getVolumn(){ 11 return shape.getArea()*height; 12 } 13 public void changeShape(xingzhuang xingzh){ 14 this.shape=xingzh; 15 } 16 }
三、运行结果: