外观模式代码举例(java语言版)

前言:外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。使用场景: 1、为复杂的模块或子系统提供外界访问的模块。 2、子系统相对独立。 3、预防低水平人员带来的风险。

JAVA语言版外观模式

创建接口:

public interface Shape {
    void draw();
}

创建接口实现类:

public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("画圆形");
    }
}

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("画矩形");
    }
}

public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("画正方形");
    }
}

创建整合操作的对外的外观类:

public class ShapeMakerAll {
    private Shape circle;
    private Shape square;
    private Shape rectangle;

    public ShapeMakerAll() {
        this.circle = new Circle();
        this.square = new Square();
        this.rectangle = new Rectangle();
    }

    public void drawAll() {
        circle.draw();
        square.draw();
        rectangle.draw();
    }
}

使用FacadePatternDome类演示使用该外观类画出各种类型的形状。

public class FacadePatternDemo {
    public static void main(String[] args) {
        ShapeMakerAll shapeMakerAll = new ShapeMakerAll();
        shapeMakerAll.drawAll();
    }
}

输出结果:

画圆形
画正方形
画矩形

猜你喜欢

转载自blog.csdn.net/qq_35386002/article/details/89476058