Facade模式(门面模式)

2020-12-16  本文已影响0人  涅槃快乐是金

门面模式(Facade Pattern):互相关联的复杂类,统一整合出对外部暴露可以访问系统的接口。这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。

介绍

注意事项:在层次化结构中,可以使用外观模式定义系统中每一层的入口。

示例

Shape.ts 模型接口
export interface Shape {
    draw(): void;
}
Rectangle.ts 矩形类
import { Shape } from "./Shape";

export default class Rectangle implements Shape {
    public draw(): void {
        console.log("Rectangle::draw()");
    }
}
Square.ts 正方形类
import { Shape } from "./Shape";

export default class Square implements Shape {

    public draw(): void {
        console.log("Square::draw()");
    }
}
Circle.ts 圆形类
import { Shape } from "./Shape";

export default class Circle implements Shape {

    public draw(): void {
        console.log("Circle::draw()");
    }
}
ShapeMaker.ts 图形绘制门面类
import { Shape } from "./Shape";
import Circle from "./Circle";
import Rectangle from "./Rectangle";
import Square from "./Square";

export default class ShapeMaker {
    private circle: Shape;
    private rectangle: Shape;
    private square: Shape;

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

    public drawCircle(): void {//绘制圆形
        this.circle.draw();
    }
    public drawRectangle(): void {//绘制矩形
        this.rectangle.draw();
    }
    public drawSquare(): void {//绘制正方形
        this.square.draw();
    }
}
index.ts
import ShapeMaker from "./ShapeMaker";

const shapeMaker: ShapeMaker = new ShapeMaker();

shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();      
result
Circle::draw()
Rectangle::draw()
Square::draw()

类图

类图

角色

上一篇 下一篇

猜你喜欢

热点阅读