一、题目
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
二、代码
1.Test.java
package c; import java.util.Scanner; import cc.Cone; import cc.Factory; public class Test { public static void main(String[] args) { while(true){ Scanner reader = new Scanner(System.in); System.out.print("请输入你选择的形状:矩形r,三角形t,圆c,梯形T,正方形Z"); char c = reader.next().charAt(0); Factory fa = new Factory(); Cone cone = new Cone(fa.getShape(c), reader.nextDouble()); System.out.print(cone.getVolume()); } } }
2.Factory
package cc; import java.util.*; public class Factory { static Shape shape=null; public static Shape getShape(char c){ switch(c){ case 'z':System.out.println("请输入以正方形为底的柱体高:"); shape=new Zheng(15);break; case 't':System.out.println("请输入以三角形为底的柱体高:"); shape=new Triangle(3,3,3);break; case 'r':System.out.println("请输入以矩形为底的柱体高:"); shape=new Rectangle(7,8);break; case 'c':System.out.println("请输入以圆形为底的柱体高:"); shape=new yuan(120);break; case 'x':System.out.println("请输入以梯形为底的柱体高:"); shape=new tixing(7,8,9);break; } return shape; } }
3.Shape
package cc; public interface Shape { double getArea(); }
4.Cone
package cc; 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; } }
5.Reactangle
package cc; public class Rectangle implements Shape { double width; double length; public Rectangle(double width,double length){ this.length = length; this.width = width; } public double getArea(){ return width * length; }}
6.yuan
package cc; public class yuan implements Shape { double r; double PI=3.14; public yuan(double r){ this.r=r; } public double getArea(){ return PI*r*r; } }
7.Zheng
package cc; public class Zheng extends Rectangle { public Zheng(double side){ super(side,side); } public Zheng(){ super(0,0); } public double getArea(){ return width*length; } }
8.tixing
package cc; public class tixing implements Shape { double a; double b; double height; public tixing(double a,double b,double height){ this.a=a; this.b=b; this.height=height; } public double getArea(){ return (a+b)*height/2; } }
9.triangle
package cc; public class Triangle implements Shape { double a; double b; double c; public 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.0; return Math.sqrt(p*(p-a)*(p-b)*(p-c)); } }
三、运行结果