一、题目
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,
代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
二、代码段
(1)shape类
package zcy;
public interface Shape {
public double getArea();//定义接口求面积方法
}
(2)Rectangle类
package zcy;
//定义矩形类,调用shape接口
public class Rectangle implements Shape{
public double length;
public double width;
public Rectangle(double length,double width){
this.length=length;
this.width=width;
}
public double getArea(){
return width*length;
}
}
(3)Triangle类
package zcy;
//定义三角形类调用Shape接口
public class Triangle implements Shape{
double a,b,c;
public Triangle(double a,double b,double c){
this.a=a;
this.b=b;
this.c=c;
}
public double getArea() {
double m=(a+b+c)/2;
return Math.sqrt(m*(m-a)*(m-b)*(m-c));
}
(4)TiXing类
package zcy;
//定义梯形类,调用shape接口
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;
}
}
(5)Square类
package zcy;
//定义正方形类继承矩形类
public class Square implements Shape{
double a;
public Square(double a){
this.a=a;
}
public double getArea(){
return a*a;
}
}
(6)Circle类
package zcy;
//定义圆形类,调用shape接口
public class Circle implements Shape{
double r;
public Circle(double r){
this.r=r;
}
public double getArea(){
return 3.14*r*r;
}
}
(7)Column类
package zcy;
//定义柱体类,柱体高,换底方法
public class Column {
Shape shape;
double height;
public Column(Shape shape,double height){
this.shape=shape;
this.height=height;
}
public double getVolumn(){
return shape.getArea()*height;
}
public void changeShape(Shape shape){
this.shape=shape;
}
}
(8)Factory类
package zcy;
import java.util.Scanner;
//工厂类 实现通过输入字符,自动创建对应类型的对象
public class Factory {
Shape shape=null;
Scanner reader = new Scanner(System.in);
public Shape getShape() {
char i=reader.next().charAt(0);
switch(i) {
case'y':System.out.println("以圆形为底的柱体体积是:");shape=new Circle(5);break;
case'z':System.out.println("以正方形为底的柱体体积是:");shape=new Square(6);break;
case't':System.out.println("以梯形为底的柱体体积是:");shape=new TiXing(4,5,2);break;
case'j':System.out.println("以矩形为底的柱体体积是:");shape=new Rectangle(4,5);break;
case's':System.out.println("以三角形为底的柱体体积是:");shape=new Triangle(4,5,6);break;
}
return shape;
}
}
(9)Test类
package zcy;
import java.util.Scanner;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("请输入柱体的高:");
double h;
Scanner r=new Scanner(System.in);
h=r.nextDouble();
for(int j=0;j<5;j++){
System.out.println("请选择柱体以何图形为底:“y”为圆形,“z”为正方形,“t”为梯形,“j”为矩形“s”为三角形");
Factory f=new Factory();
Column col=new Column(f.getShape(),h);
col.changeShape(f.shape);
System.out.println(col.getVolumn());
}
}
}
三、结果运行图