Proxy Pattern(代理模式)

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

代理模式(Proxy Pattern):代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。这种类型的设计模式属于结构型模式。

介绍

示例

BuyHouse.ts 创建服务类接口
export interface BuyHouse {
    buyHosue(): void;
}
BuyHouseImpl.ts 实现服务接口
import { BuyHouse } from "./BuyHouse";

export default class BuyHouseImpl implements BuyHouse {

    constructor() {

    }
    public buyHosue(): void {
        console.log("我要买房");
    }
}
BuyHouseProxy.ts 创建代理类
import { BuyHouse } from "./BuyHouse";

export default class BuyHouseProxy implements BuyHouse {
    private buyHouse: BuyHouse;
    constructor(buyHouse: BuyHouse) {
        this.buyHouse = buyHouse;
    }

    public buyHosue(): void {
        console.log("买房前准备");
        this.buyHouse.buyHosue();
        console.log("买房后装修");
    }
}
index.ts
import BuyHouseImpl from "./BuyHouseImpl";
import BuyHouseProxy from "./BuyHouseProxy";

const buyHouse = new BuyHouseImpl();
buyHouse.buyHosue();
const buyHouseProxy = new BuyHouseProxy(buyHouse);
buyHouseProxy.buyHosue();

类图

角色:

上一篇 下一篇

猜你喜欢

热点阅读