第9次作业--接口及接口回调
1、题目:
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
2、源代码
Test.java
import java.util.Scanner; /*主方法接受字母输出结果 */ public class Test { @SuppressWarnings("resource") public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("请输入底面形状的字母:"); while (true) { @SuppressWarnings("resource") Scanner reader = new Scanner(System.in); char c = reader.next().charAt(0); if (c == 'e') { System.out.println("退出"); return; } else { Factory f = new Factory(); Cone cone = new Cone(f.getShape(c), 4); System.out.println(cone.getV()); } } } }
Factory.java
/*Factory简单工厂方法 * getShape方法 * switch选择 */ public class Factory { Shape shape=null; Shape getShape(char c){ switch(c){ case't':shape=new TiXing(6,8,8);break; case'j':shape=new JuXing(5,5);break; case'z':shape=new ZhengFang(5);break; case'y':shape=new Yuan(9);break; case's':shape=new SanJiao(4,5,5);break; default:System.out.println("error"); } return shape; } }
Shape.java
/*定义Shape接口 */ public interface Shape { public double getArea(); }
Cone.java
/*Cone类 *getV方法 */ public class Cone { Shape shape; double high; public Cone(Shape shape, double high) { this.shape = shape; this.high = high; } public double getV() { return shape.getArea() * high; } }
JuXing.java
/*定义JuXing类使用Shape接口 * JuXing构造方法 * getArea方法 */ 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; } }
SanJiao.java
/*定义SanJiao类使用Shape接口 * SanJiao构造方法 * getArea方法 */ public class SanJiao implements Shape { double a; double b; double 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)); } }
TiXing.java
/*定义TiXing类使用Shape接口 * TiXing构造方法 * getArea方法 */ public class TiXing implements Shape { double a; double b; double 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; } }
Yuan.java
/*定义Yuan类使用Shape接口 * Yuan构造方法 * getArea方法 */ public class Yuan implements Shape { double r; public Yuan(double r) { this.r = r; } public double getArea() { double area = Math.PI * r * r; return area; } }
ZhengFang.java
/*定义ZhengFang类继承JuXIng * ZhengFang构造方法 * getArea方法 */ public class ZhengFang extends JuXing { public ZhengFang() { super(0, 0); } public ZhengFang(double side) { super(side, side); } public double getArea() { return width * width; } }
3.运行结果


浙公网安备 33010602011771号