题目:
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
源代码:
1.Shape.java
/**创建一个图形接口,定义一个求面积的方法*/
package cn.edu.ccut.jiekou; public interface Shape { double getArea(); }
2.JuXing.java
/**创建矩形类,定义成员变量(长和宽)和求面积的方法*/
package cn.edu.ccut.jiekou; public class JuXing implements Shape{ double length; double width; public JuXing(double length,double width){ this.length=length; this.width=width; } public double getArea(){ return length*width; } }
3.ZhengFangXing.java
/** 创建一个正方形的子类继承矩形类,创建一个有参的构造方法和求面积方法*/
package cn.edu.ccut.jiekou; public class ZhengFangXing extends JuXing{ public ZhengFangXing(double length){ super(length,length); } public double getArea(){ return length*length; } }
4.SanJiaoXing.java
/**创建三角形类,定义成员变量(a,b,c)和求面积的方法 */
package cn.edu.ccut.jiekou; public class SanJiaoXing implements Shape{ double a; double b; double c; public SanJiaoXing(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)); } }
5.TiXing.java
/**创建梯形类,定义成员变量(上底m,下底n,高h)和求面积的方法*/
package cn.edu.ccut.jiekou; public class TiXing implements Shape{ double m; double n; double h; public TiXing(double m,double n,double h){ this.m=m; this.n=n; this.h=h; } public double getArea(){ return (m+n)*h/2; } }
6.Yuan.java
/**创建圆类,定义成员变量(r和PI并初始化PI=3.14)和求面积的方法*/
package cn.edu.ccut.jiekou; 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.ZhuTi.java
/**创建柱体类,定义图形对象和高,定义求体积的方法*/
package cn.edu.ccut.jiekou; public class ZhuTi { Shape g; double h; public ZhuTi(Shape g,double h){ this.g=g; this.h=h; } public double getV(){ return g.getArea()*h; } }
8.Factory.java
/**创建一个工厂类,定义一个图形对象g,创建一个Shape类型的方法ss,方法中定义一个开关,返回图形对象g*/
package cn.edu.ccut.jiekou; public class Factory { static Shape g=null; public static Shape ss(char ch){ switch(ch){ case 'j':System.out.print("以矩形为底的柱体体积为:");g=new JuXing(6,8);break; case 'z':System.out.print("以正方形为底的柱体体积为:");g=new ZhengFangXing(6);break; case 's':System.out.print("以三角形为底的柱体体积为:");g=new SanJiaoXing(6,8,10);break; case 't':System.out.print("以梯形为底的柱体体积为:");g=new TiXing(5,7,6);break; case 'y':System.out.print("以圆形为底的柱体体积为:");g=new Yuan(9);break; } return g; } }
9.Test.java
/**创建一个Test类,定义主方法,定义一个for循环,定义一个柱体对象,调用求体积方法,输出结果*/
package cn.edu.ccut.jiekou; import java.util.Scanner; public class Test { public static void main(String[] args){ for(int i = 0;i<5;i++){ Scanner scanner=new Scanner(System.in); System.out.println("请输入图形所代表的的字符:"); char ch=scanner.next().charAt(0); ZhuTi zhuti=new ZhuTi(Factory.ss(ch),8); System.out.println(zhuti.getV()); } } }
运行结果: