一、题目
利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。
二、源代码
1.Shape.java
/** * 创建图形接口和求面积方法 */ package com; public interface Shape { double getArea(); }
2.Rectangle.java
/** * 创建矩形类:定义成员变量、一个有参的构造方法、求面积方法 */ package com; public class Rectangle implements Shape{ double a; double b; public Rectangle(double a,double b){ this.a=a; this.b=b; } @Override public double getArea() { // TODO Auto-generated method stub return a*b; } }
3.Square.java
/** * 创建正方形类:定义成员变量、一个有参的构造方法、求面积方法 */ package com; public class Square implements Shape{ double a; public Square(double a){ this.a=a; } @Override public double getArea() { // TODO Auto-generated method stub return a*a; } }
4.Triangle.java
/** * 创建三角形类:定义成员变量、一个有参的构造方法、求面积方法 */ package com; 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; } @Override public double getArea() { // TODO Auto-generated method stub double p=(a+b+c)/2; return Math.sqrt(p*(p-a)*(p-b)*(p-c)); } }
5.Circle.java
/** * 创建圆形类:定义成员变量、一个有参的构造方法、求面积方法 */ package com; public class Circle implements Shape{ double r; public Circle(double r){ this.r=r; } @Override public double getArea() { // TODO Auto-generated method stub return r*r*Math.PI; } }
6.Zoid.java
/** * 创建梯形类:定义成员变量、一个有参的构造方法、求面积方法 */ package com; public class Zoid implements Shape{ double a; double b; double h; public Zoid(double a,double b,double h){ this.a=a; this.b=b; this.h=h; } @Override public double getArea() { // TODO Auto-generated method stub return ((a+b)*h)/2; } }
7.Cone.java
/** * 创建柱体类:定义图形对象和高、创建构造方法、求体积方法 */ package com; public class Cone { Shape shape; double h; public Cone(Shape shape,double h){ this.shape=shape; this.h=h; } public double getV(){ return shape.getArea()*h; } }
8.Factory.java
/** * 创建工厂类:定义图形对象、创建一个方法返回图形对象 */ package com; public class Factory { static Shape shape=null; public static Shape shapeV(char c){ switch (c) { case 'r': System.out.println("以矩形为底的柱体体积为:"); shape=new Rectangle(6, 6);break; case 's': System.out.println("以正方形为底的柱体体积为:"); shape=new Square(9);break; case 't': System.out.println("以三角形为底的柱体体积为:"); shape=new Triangle(6, 6, 6);break; case 'c': System.out.println("以圆形为底的柱体体积为:"); shape=new Circle(6);break; case 'z': System.out.println("以梯形为底的柱体体积为:"); shape=new Zoid(9, 9, 6);break; } return shape; } }
9.Test.java
/** * 创建测试类:一个while循环,在循环中定义一个柱体对象,并调用求体积方法输出结果 * 输入f则退出循环 */ package com; import java.util.Scanner; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("请输入要求面积的图形"); System.out.println("矩形 r;正方形 s;三角形 t;圆形 c;梯形 z;"); while(true){ char c=sc.next().charAt(0); if(c=='f'){ System.out.println("退出循环"); return; } Cone cone=new Cone(Factory.shapeV(c), 6); System.out.println(cone.getV()); } } }