题目:
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
代码:
1、Test.java
1 /** 2 * 测试类 3 * 求体积; 4 */ 5 package cn.edu.ccut; 6 7 import java.util.Scanner; 8 public class Test { 9 10 public static void main(String[] args) { 12 while(true){ 13 System.out.println("柱体底的形状:"); 14 Scanner reader = new Scanner(System.in); 15 char c = reader.next().charAt(0); 20 Factory f = new Factory(); 21 Cone cone = new Cone(f.get(c) , 6); 22 System.out.println("体积: "+cone.getV()); 23 } 24 } 25 26 }
2、Factory.java
1 /** 2 * 工厂类 3 * get返回用户所需对象; 4 */ 5 package cn.edu.ccut; 6 7 public class Factory { 8 Shape shape = null;
8 9 public Shape get(char c){ 10 switch(c){ 11 case 'j':shape = new Rec(3,5);break; 12 case 's':shape = new Triangle(3,4,5);break; 13 14 case 't':shape = new Trapezoid(4,5,7);break; 15 case 'y':shape = new Circle(3);break; 16 default:System.out.println("wrong"); 17 } 18 return shape; 19 } 20 }
3、Shape.java
1 /** 2 * 图形接口; 4 */ 5 package cn.edu.ccut; 6 7 public interface Shape { 8 public double getArea(); 9 }
4、Rec.java
1 /** 2 * 实现了图形接口的矩形类包含两个成员变量并实现了getArea方法; 3 * 成员变量代表的长和宽; 5 */ 6 package cn.edu.ccut; 7 8 public class Rec implements Shape { 9 double a; 10 double b;
10 11 Rec(double a , double b){ 12 this.a = a; 13 this.b = b; 14 } 15 public double getArea(){ 16 return (a*b); 17 } 18 }
5、Circle.java
1 /** 2 * 实现了图形接口的圆类一个成员变量,两个方法; 3 * 成员变量r为半径; 4 * 5 */ 6 package cn.edu.ccut; 7 8 public class Circle implements Shape{ 9 double r; 10 11 public Circle(double r){ 12 this.r = r; 13 } 14 public double getArea(){ 15 return (Math.PI*r*r); 16 } 17 }
6、Triangle.java
1 /** 2 * 三角形类三个成员变量,两个方法; 3 * 成员变量a,b,c代表三个边; 4 * 5 */ 6 package cn.edu.ccut; 7 8 public class Triangle implements Shape{ 9 double a; 10 double b; 11 double c; 12 13 public Triangle (double a , double b , double c){ 14 this.a = a; 15 this.b = b; 16 this.c = c; 17 } 18 public double getArea(){ 19 double p = (a + b + c) / 2; 20 return Math.sqrt(p * (p - a) * (p - b) * (p - c)); 21 } 22 }
7、Trapezoid.java
1 /** 2 * 梯形类包含三个成员变量,两个方法; 3 * a,b代表上底和下底,height代表高; 4 * 5 */ 6 package cn.edu.ccut; 7 8 public class Trapezoid implements Shape{ 9 double a; 10 double b; 11 double height; 12 13 public Trapezoid(double a , double b , double height){ 14 this.a = a; 15 this.b = b; 16 this.height = height; 17 } 18 public double getArea(){ 19 return (((a + b) * height) / 2); 20 } 21 }
8、Cone.java
1 /** 2 * 柱体类两个成员变量,三个方法; 3 * shape代表底,height代表高; 4 * 5 */ 6 package cn.edu.ccut; 7 8 public class Cone { 9 Shape shape; 10 double height;
10 11 public Cone(Shape shape , double height){ 12 this.shape = shape; 13 this.height = height; 14 } 15 public double getV(){ 16 return (shape.getArea()*height); 17 } 18 public void setDi(Shape shape){ 19 this.shape = shape; 20 } 21 }
运行结果: