第九次作业-接口及接口回调
一、题目:
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
二、代码:
定义接口 Shape
1 2 3 4 5 |
package tiji;
public interface Shape { public double getArea(); } |
定义 矩形类,调用Shape接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package tiji;
public class JvXing implements Shape { public double width; public double length;
public JvXing(double width,double length){ this.width=width; this.length=length; }
public double getArea(){ return width*length; } } |
定义三角类,调用Shape接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package tiji;
public class SanJiao implements Shape{ double a,b,c;
public SanJiao(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)); }
} |
定义梯形类,调用Shape接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package tiji;
public class TiXing implements Shape { double a,b,h;
public TiXing(double a,double b,double h){ this.a=a; this.b=b; this.h=h; }
public double getArea(){ return (a+b)*h/2; } } |
定义圆形类,调用Shape接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package tiji;
public class Yuan implements Shape{ double r;
public Yuan(double r){ this.r=r; }
public double getArea() { return 3.14*r*r; }
} |
定义正方形类,继承矩形类
1 2 3 4 5 6 7 8 9 10 11 12 |
package tiji;
public class ZhengFang extends JvXing{
public ZhengFang(int width) { this(width,width); }
public double getArea(){ return width*width; } } |
定义柱体类,实现求体积和换底求体积的功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package tiji;
public class ZhuTi { Shape shape; double height;
public ZhuTi(Shape shape,double height){ this.shape=shape; this.height=height; }
public double getV(){ return shape.getArea()*height; }
public void changeShape(Shape shape){ this.shape=shape; } } |
定义工厂类,实现通过输入的字符,自动创建对应类型的对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package tiji;
public class factory { //Scanner r=new Scanner(System.in); Shape getShape(char c){ Shape shape=null;
switch(c){ case 'j':shape=new JvXing(5,6);break; case 's':shape=new SanJiao(5,6,7);break; case 't':shape=new TiXing(4,5,6);break; case 'y':shape=new Yuan(5);break; case 'z':shape=new ZhengFang(5);break; } return shape; }
} |
主类,程序的 入口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package tiji; import java.util.*; import tiji.ZhuTi; import tiji.factory;
public class test {
/** * @param args */ public static void main(String[] args) { Scanner r=new Scanner(System.in); char c=r.next().charAt(0); factory f=new factory(); f.getShape(c); ZhuTi z=new ZhuTi(f.getShape(c),5); System.out.println("体积是:"+z.getV()); System.out.print("请输入柱体新底的类型:"); c=r.next().charAt(0); z.changeShape(f.getShape(c)); System.out.println("换底后的体积:"+z.getV()); }
} |
三、实现