一、题目
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
二、源程序
1. Shape.java
package work; public interface Shape { //接口 double getArea(); }
2.Factory.java
package work; import java.util.*; public class Factory {//工厂类 static Shape shape = null; public static Shape k(char c) {//根据用户输入字母 判断柱体底面 switch (c) { case 'J': System.out.println("矩形柱体高为:"); shape = new Juxing(4, 5); break; case 'Z': System.out.println("正方形柱体高为:"); shape = new Zheng(5); break; case 'S': System.out.println("三角形柱体高为:"); shape = new San(4, 5, 6); break; case 'Y': System.out.println("圆形柱体高为:"); shape = new Yuan(5, 3.14); break; case 'T': System.out.println("梯形柱体高为:"); shape = new Tixing(4, 5, 7); break; } return shape; } }
3.Cone.java
package work; 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 setRect(Shape shape) { this.shape = shape; } }
4.Jvxing.java
package work; public class Juxing implements Shape {//创建矩形类使用接口 double width; double length; public Juxing(double width, double length) { this.width = width; this.length = length; } public double getArea() { //计算矩形面积 return width * length; } }
5.Zheng.java
package work; public class Zheng extends Juxing {//创建矩形子类正方形 public Zheng(double side) { super(side, side); } public Zheng() { super(0, 0); } public double getArea() { //计算面积 return width * width; } }
6.San.java
package work; public class San implements Shape {//创建三角形类使用接口 double a; double b; double c; public San(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)); } }
7.Yuan.java
package work; public class Yuan implements Shape {//创建圆形类使用接口 double r; double PI = 3.14; public Yuan(double r, double PI) { this.r = r; } public double getArea() { //计算面积 return PI * r * r; } }
8.Tixing.java
package work; public class Tixing implements Shape {//创建梯形类使用接口 double s; double x; double h; public Tixing(double s, double x, double h) { this.s = s; this.x = x; this.h = h; } public double getArea() { //计算体积 return (s + x) * h / 2; } }
9.Test.java
package work; import java.util.Scanner; import work.Cone; import work.Factory; public class Text { public static void main(String[] args) {//创建一个主方法 while (true) { Scanner reader = new Scanner(System.in); System.out.println("输入对应字母:"); char c = reader.next().charAt(0); Factory factory = new Factory(); Cone cone = new Cone(factory.k(c), reader.nextDouble()); System.out.println("体积为:" + cone.getVolume()); } } }
三、运算结果