题目:
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
一, 长方形代码(包含在yyy包内,使用接口,两个成员变量 一个求面积方法)
package yyy;
public class cfx implements Shape{
double a; //a是长
double b; //b是宽
public cfx( double a,double b){
this.a=a;
this.b=b;
}
public double getArea(){
return a*b;
}
}
二,正方形代码 (包含在yyy包内,继承cfx类, 一个求面积方法)
package yyy;
public class zheng extends cfx {
public zheng(double c) {
super(c, c); //正方形边长
}
public double getArea(){
return a*a ;
}
}
三,三角形代码(包含在yyy包内,使用接口,三个成员变量 一个求面积方法)
package yyy;
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));
}
}
四,梯形代码(包含在yyy包内,使用接口,三个成员变量 一个求面积方法)
package yyy;
public class tixing implements Shape {
double a;
double b;
double height;
public tixing(double a,double b,double height){
this.a=a;
this.b=b;
this.height=height;
}
public double getArea(){
return (a+b)*height/2;
}
}
五,圆形代码(包含在yyy包内,使用接口,一个成员变量 一个求面积方法)
package yyy;
public class yuan implements Shape {
double radius;
double PI=3.14;
public yuan(double radius){
this.radius=radius;
}
public double getArea(){
return PI*radius*radius;
}
}
六,接口
package yyy;
public interface Shape {
double getArea();
}
七,工厂(使用switch判别图形进行相应的求面积算法)
package yyy;
import java.util.Scanner;
public class Factory {
static Shape getShape(char c) {
Scanner reader = new Scanner(System.in);
Shape shape = null;
switch (c) {
case 'j':
System.out.print("请输入矩形的长和宽
柱体的高
");
shape = new cfx(reader.nextDouble(), reader.nextDouble());
break;
case 's':
System.out.print("请输入三角形的三条边,
柱体的高
");
shape = new sanjiao(reader.nextDouble(), reader.nextDouble(), reader.nextDouble());
break;
case 'y':
System.out.print("请输入圆的半径,
柱体的高
");
shape = new yuan(reader.nextDouble());
break;
case 't':
System.out.print("请输入梯形的上底下底
和高
柱体高
z");
shape = new tixing(reader.nextDouble(), reader.nextDouble(), reader.nextDouble());
break;
case 'z':
System.out.print("请输入正方形的边长,
柱体的高
");
shape = new zheng(reader.nextDouble());
break;
}
return shape;
}
}
八,Text
package yyy;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
while(true){
Scanner reader = new Scanner(System.in);
System.out.print("请输入你选择的形状:矩形j,三角形s,圆y,梯形t,正方形z");
char c = reader.next().charAt(0);
Cone cone = new Cone(Factory.getShape(c), reader.nextDouble());
System.out.print(cone.getVolume());
}
}
}
九
package yyy;
public class Cone {
Shape shape;
double high;
public Cone(Shape shape, double high) {
this.shape = shape;
this.high = high;
}
public double getVolume() {
return shape.getArea()*high;
}
}
十,结果