题目:利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
代码实现:
//*定义一个shape接口用来做柱体的底*// package cn.edu.ccut.po; public interface Shape { abstract double getArea(); }
//*定义圆形类继承shape接口*// package cn.edu.ccut.po; public class Circle implements Shape{ final double PI=3.14; double r; Circle(double r){ this.r=r; } public double getArea(){ return PI*r*r; } }
//*定义一个矩形类继承shape结口*// package cn.edu.ccut.po; public class Rectangle implements Shape{ double width; double length; Rectangle(double width,double length){ this.length=length; this.width=width; } public double getArea(){ return width*length; } }
//*定义一个正方形类继承shape接口*// package cn.edu.ccut.po; public class Square implements Shape { double length; double area; Square(double length){ this.length=length; } public double getArea(){ return area=length*length; } }
//*定义一个梯形类继承shape接口*// package cn.edu.ccut.po; public class Trapezoid implements Shape{ double shangdi; double xiadi; double height; Trapezoid(double shangdi,double xiadi,double height){ this.shangdi=shangdi; this.xiadi=xiadi; this.height=height; } public double getArea(){ return(shangdi+xiadi)*height/2; } }
//*定义一个三角形类继承shape接口*// package cn.edu.ccut.po; public class Triangle implements Shape{ double a; double b; double c; Triangle(double a,double b,double c){ this.a=a; this.b=b; this.c=c; } public double getArea(){ double p=(a+b+c)/2; return Math.sqrt(p*(p-a)*(p-b)*(p-c)); } }
//*定义柱体类,定义一个换底方法*// package cn.edu.ccut.po; public class Cone { Shape shape; double high; public Cone(Shape shape,double high){ this.shape=shape; this.high=high; } public double getVolume(){ return shape.getArea()*high; } public void setShape(Shape shape){ this.shape=shape; } }
//*创建一个工厂类,并用switch语句选择柱体的底的形状*// package cn.edu.ccut.po; import java.util.*; public class Factory { Shape shape=null; Scanner input=new Scanner(System.in); public Factory(double height){ Cone cone=new Cone(this.getShape(),height); System.out.println(cone.getVolume()); } public Shape getShape(){ System.out.println("请选择底的图形:矩形:R;正方形:S;圆形:C;三角形:V;梯形:T"); char A=input.next().charAt(0); switch(A){ case'R':System.out.println("以矩形为底的柱体体积为:");shape=new Rectangle(5,8);break; case'S':System.out.println("以正方形为底的柱体体积为:");shape=new Square(6);break; case'C':System.out.println("以圆形为底的柱体体积为:");shape=new Circle(2);break; case'V':System.out.println("以三角形为底的柱体体积为:");shape=new Triangle(5,3,4);break; case'T':System.out.println("以梯形为底的柱体体积为:");shape=new Trapezoid(4,5,9);break; } return shape; } }
//*测试类*// package cn.edu.ccut.po; public class Text { public static void main(String[] args) { double height=8; Factory factory=new Factory(height); } }
运行结果: