利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
Shape类(图形类)
/**创建一个图形类接口,一个求面积抽象方法*/
package ccut.li;
public interface Shape {
abstract double getArea();
}
yuanxing类(圆形类)
/**创建一个圆类继承shape接口,定义半径r,PI,圆的构造方法和重写求面积方法*/
package ccut.li;
public class yuanxing implements Shape{
double r;
final double PI=3.14;
yuanxing(double r){
this.r=r;
}
public double getArea(){
return r*r*PI;
}
}
zhengfangxing类(正方形类)
/**创建一个正方形类继承shape接口,定义边长a,正方形构造方法和重写求面积方法*/
package ccut.li;
public class zhengfangxing implements Shape{
double a;
public double getArea(){
return a*a;
}
zhengfangxing(double a){
this.a=a ;
}
}
tixing类(梯形类)
/**创建一个梯形类继承shape接口,定义上底a,下底b,高h,梯形构造方法和重写求面积方法*/
package ccut.li;
public class tixing implements Shape{
double a;
double b;
double h;
tixing(double a,double b,double h){
this.a=a;
this.b=b;
this.h=h;
}
public double getArea(){
return (a+b)*h/2;
}
}
juxing类(矩形类)
/** 创建一个矩形类继承shape接口,定义长a,宽b,矩形构造方法和重写求面积方法*/
package ccut.li;
public class juxing implements Shape {
double a;
double b;
public double getArea(){
return a*b;
}
juxing(double a,double b){
this.a=a;
this.b=b;
}
}
sanjiao类(三角形类)
/**创建一个三角形类继承shape接口,定义三边a,b,c,三角形构造方法和重写求面积方法*/
package ccut.li;
public class sanjiao implements Shape{
double a;
double b;
double c;
sanjiao(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.li;
public class zhuTi {
double h;
Shape shape;
public zhuTi(double h,
int i) {
}
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.li;
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'a':System.out.println("以圆形为底的柱体体积是:");shape=new yuanxing(5);break;
case'b':System.out.println("以正方形为底的柱体体积是:");shape=new zhengfangxing(6);break;
case'c':System.out.println("以梯形为底的柱体体积是:");shape=new tixing(4,5,2);break;
case'd':System.out.println("以矩形为底的柱体体积是:");shape=new juxing(4,5);break;
case'e':System.out.println("以三角形为底的柱体体积是:");shape=new sanjiao(4,5,6);break;
}
return shape;
}
}
lisq1类(主类)
/**提示用户输入,定义高h,用for循环输出五个图形为底的体积,创建一个工厂类对象,一个柱体类对象,引用换底方法,输出柱体的体积*/
package ccut.li;
import java.util.*;
public class lisq1 {
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("请选择柱体以何图形为底:“a”为圆形,“b”为正方形,“c”为梯形,“d”为矩形,“e”为三角形");
Factory f=new Factory();
zhuTi zt=new zhuTi(h,f.getShape());
zt.setShape(f.shape);
System.out.println(zt.getV());
}
}
}