一、题目:
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
二、源代码
Shape.java
package a.b; /* * 建一个形状接口,求面积的抽象方法 */ public interface Shape { double getArea(); }
Rectangle.java
package a.b; /* * 求长方形面积 */ public class Rectangle implements Shape { double width; double length; public Rectangle(double width,double length) { this.width=width; this.length=length; } public double getArea() { return width*length; } }
Zheng.java
package a.b; /* * 求正方形面积 */ public class Zheng extends Rectangle { public Zheng(double side) { super(side,side); } public Zheng(){ super(0,0); } public double getArea() { return width*width; } }
Trangle.java
package a.b; /* * 计算三角形面积 */ public class Trangle implements Shape { double a; double b; double c; public Trangle(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)); } }
Circle.java
package a.b; /* * 求圆面积 */ public class Circle implements Shape { public final static double PI=3.14; double r; public Circle(double r) { this.r=r; } public double getArea() { return r*r*PI; } }
Trapezoid.java
package a.b; /* * 求梯形面积 */ public class Trapezoid implements Shape { double sd; double xd; double h; public Trapezoid(double sd,double xd,double h) { this.sd=sd; this.xd=xd; this.h=h; } @Override public double getArea() { return (sd+xd)*h/2; } }
Cone.java
package a.b; /* * 定义一个柱体类利用接口回调求体积 */ 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; //接口回调 } }
Factory.java
package a.b; /* * 键一个工厂类 */ import java.util.*; public class Factory { Shape getShape(char c) { Scanner sc = new Scanner(System.in); Shape shape = null; switch(c) { case 'r': System.out.println("请输入矩形的长和宽"); shape = new Rectangle(sc.nextInt(), sc.nextDouble()); break; case 'z': System.out.println("请输入正方形的边长"); shape = new Zheng(sc.nextDouble()); break; case 's': System.out.println("输入三角形的边长"); shape=new Trangle(sc.nextDouble(),sc.nextDouble(),sc.nextDouble()); break; case'c': System.out.println("请输入圆形的半径"); shape=new Circle(sc.nextDouble()); break; case't': System.out.println("请输入梯形的上底、下底和高"); shape=new Trapezoid(sc.nextDouble(),sc.nextDouble(),sc.nextDouble()); break; } return shape; } }
Test.java
package a.b; import java.util.*; public class Test { public static void main(String[] args) { while(true) { Scanner in=new Scanner(System.in); System.out.println("输入要计算的形状和柱体的高:长方形(r) 正方形(z) 三角形(s) 圆形(c) 梯形(t)"); char c=in.next().charAt(0); Factory factory=new Factory(); Cone cone = new Cone(factory.getShape(c), in.nextDouble()); System.out.println(cone.getVolume()); } } }
三、运行结果