第9次作业--接口及接口回调
题目:利用接口和接口回调,实现简单工厂模式,当输入不同字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
一.源代码(Shape.java)
package W;
//形状接口
public interface Shape {
double getArea();
}
二.源代码(Rectangle.java)
package W;
//定义矩形类 创建两个成员变量长和宽
public class Rectangle implements Shape {
double width;
double length;
public Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
public double getArea() {
return width * length;
}
}
三.源代码(Zheng.java)
package W;
public class Zheng extends Rectangle {
public Zheng(double side) {
super(side, side);
}
public double getArea() {
return width * width;
}
}
四.源代码(Triangle.java)
package W;
public class Triangle implements Shape {
double a;
double b;
double c;
public Triangle(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));
}
}
五.源代码(T.java)
package W;
//梯形类
public class T implements Shape {
double a;
double b;
double height;
public T(double a,double b,double height){
this.a=a;
this.b=b;
this.height=height;
}
public double getArea(){
return (a+b)*height/2;
}
}
六.源代码(Circle.java)
package W;
//创建一个圆类
public class Circle implements Shape {
double radius;
double PI=3.14;
public Circle(double radius){
this.radius=radius;
}
public double getArea(){
return PI*radius*radius;
}
}
七.源代码(Cone.java)
package W;
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;
}
}
八.源代码(Foctory.java)
package W;
//创建一个工厂类
import java.util.Scanner;
public class Foctory {
Shape getShape(char c) {
Scanner reader = new Scanner(System.in);
Shape shape = null;
switch (c) {
case 'r':
System.out.print("请输入矩形的长和宽、柱体的高\n");
shape = new Rectangle(reader.nextInt(), reader.nextDouble());
break;
case 't':
System.out.print("请输入三角形的三条边,柱体的高\n");
shape = new Triangle(reader.nextDouble(), reader.nextDouble(), reader.nextDouble());
break;
case 'c':
System.out.print("请输入圆的半径,柱体的高\n");
shape = new Circle(reader.nextDouble());
break;
case 'T':
System.out.print("请输入梯形的上底下底和高\n");
shape = new T(reader.nextDouble(), reader.nextDouble(), reader.nextDouble());
break;
case 'Z':
System.out.print("请输入正方形的边长,柱体的高\n");
shape = new Zheng(reader.nextDouble());
break;
}
return shape;
}
}
九.源代码(Test.java)
package W;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
while(true){
Scanner reader = new Scanner(System.in);
System.out.print("请输入你选择的形状:矩形r,三角形t,圆c,梯形T,正方形Z");
char c = reader.next().charAt(0);
Foctory f = new Foctory();
Cone cone = new Cone(f.getShape(c), reader.nextDouble());
System.out.print(cone.getVolume());
}
}
}
十.成功截图