码迷,mamicode.com
首页 > 其他好文 > 详细

接口及接口回调

时间:2019-10-14 14:52:45      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:正方形   vol   int   const   bre   code   alt   模式   end   

题目:

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

package Test;

public class test9 {

    public static void main(String[] args) {
        Factory fa=new Factory(‘s‘);
        Prism pri=new Prism(fa.getShape(),6);
        pri.setShape(fa.getShape());
        double vol=pri.getVolumn();
        System.out.println(vol);
    }
}
//图形类
interface Shape{
    double getArea();
}
//长方形类
class Rectangle2 implements Shape {
    double width;
    double length;
    
    public Rectangle2(double width,double length) {
        this.width = width;
        this.length = length;
    }

    @Override
    public double getArea() {
        // TODO Auto-generated method stub
        return width*length;
    }
}
//正方形类
class Square2 extends Rectangle2{
    
    public Square2(double lenside) {
        super(lenside, lenside);
        // TODO Auto-generated constructor stub
    }
    public double getArea() {
        return width* length;
    }
}
//三角形类
class Triangle implements Shape{
    double lenside1;
    double lenside2;
    double lenside3;
    public Triangle(double lenside1,double lenside2,double lenside3) {
        this.lenside1 = lenside1;
        this.lenside2 = lenside3;
        this.lenside3 = lenside3;
    }
    @Override
    public double getArea() {
        // TODO Auto-generated method stub
        double count = (lenside1+lenside2+lenside3)/2;
        return Math.sqrt(count*(count-lenside1)*(count-lenside2)*(count-lenside3));
    }
}
//棱柱类
class Prism {
    Shape shape;
    double hight;
    public Prism(Shape shape,double hight) {
        this.hight = hight;
        this.shape = shape;
    }
    public double getVolumn() {
        return shape.getArea()*hight;
    }
    public void setShape(Shape shape) {
        this.shape = shape;
    }
}
//圆类
class Circle implements Shape{
    double r;
    final double PI=3.14;
    Circle(double r){
        this.r=r;
    }
    public double getArea(){
        return PI*r*r;
    }
}
//工厂
class Factory{
     Shape shape;
     char ch;
     //s.next().charAt(0);
     Factory(char ch){
         this.ch = ch;
     }
     public Shape getShape(){
         switch(ch){
         case ‘t‘:shape=new Triangle(1,2,3);break;
         case ‘r‘:shape=new Rectangle2(4,5);break;
         case ‘s‘:shape=new Square2(6);break;
         case ‘c‘:shape=new Circle(7);break;
         }
         return shape;
     }
     public char getCh(){
         return ch;
         }
     public void setShape(Shape shape){
         this.shape=shape;
         }
     public void setCh(char ch){
         this.ch=ch;
     }
}

技术图片

接口及接口回调

标签:正方形   vol   int   const   bre   code   alt   模式   end   

原文地址:https://www.cnblogs.com/xiexiaofei/p/11671163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!