接口及接口回调

Posted xiexiaofei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了接口及接口回调相关的知识,希望对你有一定的参考价值。

题目:

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

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;
     }
}

技术图片

以上是关于接口及接口回调的主要内容,如果未能解决你的问题,请参考以下文章

Java 接口及接口回调_Chris

Spring Boot启动过程及回调接口汇总

接口及接口回调

如何使用 onSaveInstanceState 在我的片段上保存和恢复接口

Flask 编写http接口api及接口自动化测试

片段交互回调:onAttach() vs setter