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

题目:

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

Shape

/**
 * 定义一个接口shape 一个getarea方法
 *
 */
package com;
public interface Shape {
    double getarea();

}

Ju

/**
 * 一个Ju类实现接口Shape 2个变量 一个有参的构造方法 实现接口shape的方法getarea
 */
package com;

public class Ju implements Shape {
    double a;
    double b;
    Ju(double a,double b){
        this.a=a;
        this.b=b;
    }
    public double getarea() {        
        return a*b;
    }

}

Zheng

/**
 * 实现接口shape的方法getarea 一个double变量 一个有参的构造方法
 */
package com;

public class Zheng implements Shape {
    double a;
    Zheng(double a){
        this.a=a;
    }
    
    public double getarea(){
        return a*a;
    }
    

}

Circle

/**
 * 一个实现接口shape中的getarea方法 一个double的变量 一个有参的构造方法
 */
package com;

public class circle implements Shape{
    double r;
    public circle(double r) {
        // TODO Auto-generated constructor stub
        this.r=r;
    }
    @Override
    public double getarea() {
        // TODO Auto-generated method stub
        return Math.PI*r*r;
    }
    

}

Triangle

/**
 * 实现接口shape中的方法 3个变量 一个有参的构造方法
 */
package com;

public class Triangle implements Shape{
    double a,b,c;
    @Override
    public double getarea() {
        double p=(a+b+c)/2;
        return Math.sqrt(p*(p-a)*(p-b)*(p-c));
    }
    Triangle(double a,double b,double c){
        this.a=a;
        this.b=b;
        this.c=c;        
    }

}

Cone

/**
 * 一个shape的变量,一个double的变量 一个有参的构造方法
 * 一个计算体积的方法
 */
package com;

public class Cone {
    Shape shape;
    double hight;
    Cone(Shape shape,double hight){
        this.shape=shape;
        this.hight=hight;
    }
    void getV(){
        System.out.println("面积是"+shape.getarea()*hight);
    }

}

factory

/**
 * 定义个shape的变量为null 一个有参的返回类型为shape的方法 
 */
package com;

public class Factory {
    static Shape shape=null;
    public static Shape getV(char c){
        switch (c) {
        case 'j':
            shape=new Ju(3,2);break;    
        case 'z':
            shape=new Zheng(4);break;
        case 't':
            shape=new Triangle(3, 4, 5);break;
        case 'c':
            shape=new circle(2);break;        
        }        
        return shape;
    }

}

Text

/**
 * 一个char的变量c  永真循环当c==0的时候结束循环  定义cone对象  利用factory获得图形对象换地
 * 调用cone中计算体积的方法
 */
package com;
import java.util.Scanner;
public class Text {
    public static void main(String[] args) {
        System.out.println("0结束程序");
        Scanner reader=new Scanner (System.in);
        while(true){
            char c=reader.next().charAt(0);
            if(c=='0')break;
            Cone con=new Cone(Factory.getV(c), 2);
            con.getV();
            
            
        }
        
        

    }

}

三,运行界面

 

原文地址:https://www.cnblogs.com/mai98/p/11616337.html