第9次作业--接口及接口回调
题目: 利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
代码及注释:
package Cylinder; import java.util.*; /**定义接口 接口方法;定义一个矩形类实现求面积的的接口方法;*/ interface Shape{ double getArea(); } /**定义一个矩形类,构造方法传入值,实现求面积的的接口方法;*/ class Rect implements Shape{ double width; double length; Rect(double width,double length){ this.width=width; this.length=length; } public double getArea() { return width*length; } } /**定义一个正方形类,构造方法传入值,实现求面积的的接口方法;*/ class Square implements Shape{ double length; Square(double length){ this.length=length; } public double getArea() { return length*length; } } /**定义一个三角形类,构造方法传入值,利用数学公式实现求面积的的接口方法;*/ class Triangle implements Shape{ double a,b,c; Triangle(double a,double b,double c){ this.a=a; this.b=b; this.c=c; } public double getArea() { double d= (a+b+c)/2; return Math.sqrt(d*(d-a)*(d-b)*(d-c)); } } /**定义一个圆形类,构造方法传入值,实现求面积的的接口方法;*/ class Circle implements Shape{ double r; public Circle(double r){ this.r=r; } public double getArea(){ return Math.PI*r*r; } } /**定义一个梯形类,构造方法传入值,实现求面积的的接口方法;*/ class Trapezoid implements Shape{ double a,b,h; Trapezoid(double a,double b,double h){ this.a=a; this.b=b; this.h=h; } public double getArea() { return (a+b)*h/2; } } /**定义一个柱体类,构造方法传入值,定义求柱体面积的方法和换底方法*/ class Cone{ Shape shape; double high; Cone(Shape shape ,double high){ this.shape=shape; this.high=high; } double getVolume() { return shape.getArea()*high; } void setShape(Shape shape){ this.shape =shape; } } /**定义一个工厂类,利用简单工厂模式利用Switch将需要的值传递给图形类*/ class Factory{ Shape shape; Scanner rea=new Scanner(System.in); char ch=rea.next().charAt(0); public Shape getShape(){ switch(ch){ case 's': shape = new Triangle(9,3,7); break; case 'c': shape = new Circle(5); break; case 'r': shape = new Rect(3,7); break; case 'z': shape = new Square(9); break; case 't': shape = new Trapezoid(6,3,3); break; } return shape; } } /**主方法利用循环输入需要求的图形并创建对象*/ public class Test { public static void main(String[] args) { System.out.println("输入柱体的高;"); Scanner reader = new Scanner(System.in); double number = reader.nextDouble(); for(int j=0;j<5;j++){ System.out.println("请选择柱体以何图形为底:"); Factory area=new Factory(); Cone volume = new Cone(area.getShape(),number); volume.setShape(area.shape); System.out.println(volume.getVolume()); } } }
运行截图: