第9次作业--接口及接口回调

1.题目:

       利用接口和接口回调,实现简单工厂模式,当输入不同的字符,代表相应图形时,利用工厂类获得图形对象,再计算以该图形为底的柱体体积。

2.代码:

/**定义接口shape 一个求面积的抽象方法,一个常规量pai
 * 
 */
package homework1_1;

public interface Shape {
    double pai=3.14;
    public double getArea();

}
/**定义rectangle类,用chang代表长方形的长,kuan代表长方形的宽,构造长方形;其中含有有一个zhouchang方法用来求周长
一个getarea用来求面积
 * 
 */
package homework1_1;

public class rectangle implements Shape{
 double chang;
 double kuan;
 rectangle(double chang,double kuan){
     this.chang=chang;
     this.kuan=kuan;
 }
 public double zhouchang(){
     double c=(chang+kuan)*2;
     return c;
 }
 public double getArea(){
     return chang*kuan;
 }
}
/**定义子类square继承父类rectangle,其中由两个方法,getarea代表求面积,zhouchang代表求周长;
 */
package homework1_1;

public class square extends rectangle{
    square(double side){
        super(side,side);
    }
    public double getArea(){
        return chang*chang;
    }
    public double zhouchang(){
         double c=chang*4;
         return c;
    }
}
 
  
 
 
/**一个三角形类,有自身的求面积方法;
 * 
 */
package homework1_1;

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 d=(a+b+c)/2;
        return Math.sqrt(d*(d-a)*(d-b)*(d-c));
    }
}
/**定义柱体类 用shape所引用的底面积和自身的高,方法getvolume求体积,setarea改类型;
 * *
 */
package homework1_1;

    public class Cone {
        Shape shape;
        double height;
        Cone(Shape shape,double height){
            this.shape=shape;
            this.height=height;
        }
     public double getVolume(){
         return shape.getArea()*height;
         
     }
     public void setArea(Shape shape){
         this.shape=shape;
     }
    }
/**factory类功能为根据用户传的字符来或许什么类型的shape;
 * 
 */
package homework1_1;

public  class factory{
    static Shape shape=null;
    
    public static  Shape whatShape(char c){
    switch(c){
    case 'r': shape = new rectangle(5,3);break;
    case 't': shape = new Triangle(5,3,6);break;
    case 's': shape = new square(5);break;
    case 'c': shape = new circle(5);break;
    }
     return shape;
}
}
/**定义一个主类T,根据上传的字符获取不同的底,创建柱体对象给与参数输出体积;

 * 
 */
package homework1_1;

import java.util.Scanner;

public class T {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in=new Scanner(System.in);
        System.out.println("请输入字符:");
        char c=in.next().charAt(0);
        Cone cone=new Cone(factory.whatShape(c),5);
    System.out.println(cone.getVolume());
    }
    
    }

3.运行结果:

猜你喜欢

转载自www.cnblogs.com/sdw98/p/11610846.html