利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
Shape类(图形类)
/**创建一个图形类接口,一个求面积抽象方法*/
package ccut.ch;
public interface Shape {
abstract double getArea();
}
Yuan类(圆形类)
/**创建一个圆类继承shape接口,定义半径r,PI,圆的构造方法和重写求面积方法*/
package ccut.ch;
public class Yuan implements Shape{
double r;
final double PI=3.14;
Yuan(double r){
this.r=r;
}
public double getArea(){
return r*r*PI;
}
}
ZFX类(正方形类)
/**创建一个正方形类继承shape接口,定义边长a,正方形构造方法和重写求面积方法*/
package ccut.ch;
public class ZFX implements Shape {
double a;
public double getArea(){
return a*a;
}
ZFX(double a){
this.a=a ;
}
}
Tx类(梯形类)
/**创建一个梯形类继承shape接口,定义上底a,下底b,高h,梯形构造方法和重写求面积方法*/
package ccut.ch;
public class Tx implements Shape{
double a;
double b;
double h;
Tx(double a,double b,double h){
this.a=a;
this.b=b;
this.h=h;
}
public double getArea(){
return (a+b)*h/2;
}
}
Rectangle类(矩形类)
/** 创建一个矩形类继承shape接口,定义长a,宽b,矩形构造方法和重写求面积方法*/
package ccut.ch;
public class Rectangle implements Shape {
double a;
double b;
public double getArea(){
return a*b;
}
Rectangle(double a,double b){
this.a=a;
this.b=b;
}
}
Triangle类(三角形类)
/**创建一个三角形类继承shape接口,定义三边a,b,c,三角形构造方法和重写求面积方法*/
package ccut.ch;
public class Triangle implements Shape{
double a;
double b;
double c;
Triangle(double a,double b,double c){
this.a=a;
this.b=b;
this.c=c;
}
public double getArea(){
double q = (a + b + c) / 2;
return Math.sqrt(q*(q-a)*(q-b)*(q-c));
}
}
ZhuTi类(柱体类)
/**创建一个柱体类,定义柱体的高h,图形shape,换底方法,求体积方法和构造方法*/
package ccut.ch;
public class ZhuTi {
double h;
Shape shape;
public void setShape(Shape shape){
this.shape=shape;
}
public double getV(){
return h*shape.getArea();
}
ZhuTi(double h,Shape shape){
this.h=h;
this.shape=shape;
}
}
Factory类(工厂类)
/**创建一个工厂类,创建一个图形对象设为空,引用输入操作提示用户输入字符,利用switch语句给柱体赋底*/
package ccut.ch;
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 Yuan(5);break;
case'z':System.out.println("以正方形为底的柱体体积是:");shape=new ZFX(6);break;
case't':System.out.println("以梯形为底的柱体体积是:");shape=new Tx(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;
}
}
Test类(主类)
/**提示用户输入,定义高h,用for循环输出五个图形为底的体积,创建一个工厂类对象,一个柱体类对象,引用换底方法,输出柱体的体积*/
package ccut.ch;
import java.util.*;
public class Test {
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();
ZhuTi zt=new ZhuTi(h,f.getShape());
zt.setShape(f.shape);
System.out.println(zt.getV());
}
}
}
运行结果