TypeScript代理模式/委托模式

interface proxyInterface {

    dofirst();

}

interface player {

    dodoA(): void;

}

 

class beProxy implements player {

    public constructor() {

        YBLog.log("beProxy", " 我是被代理的那个人 ");

    }

    public dodoA(): void {

        YBLog.log("beProxy", "  我是被代理的那个人  dodoA ");

    }

 

 

}

//代理者

class proxy implements player,proxyInterface {

    private beProxy:player = null ; //代理我的那个人

    public constructor() {

        YBLog.log("proxy", " 我是代理者  创建 一个 被代理人");

        this.beProxy = new beProxy();

    }

    public dodoA(): void {    

        this.dofirst();

        YBLog.log("proxy", "  我是代理者  dodoA 使用个性的方法 同时调用了被代理者的方法 ");

        this.beProxy.dodoA()

    }

    public dofirst(): void {

        YBLog.log("proxy", " 我是代理者  可以先做我一下自己的事情");

    }

}

new proxy().dodoA();

一.优点:高扩展,可以保留beProxy 的东西不变,直接扩展proxy的 完成一些额外的工作。

二缺点:内存大了。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
代理模式是一种结构型设计模式,它允许你提供一个代理对象,用来控制对另一个对象的访问。在 TypeScript 中,可以使用接口来定义代理对象和被代理对象的共同接口,并使用类来实现代理对象和被代理对象。 下面是一个简单的 TypeScript 代理模式示例: ```typescript interface Subject { request(): void; } class RealSubject implements Subject { public request(): void { console.log("RealSubject: Handling request."); } } class Proxy implements Subject { private realSubject: RealSubject; constructor(realSubject: RealSubject) { this.realSubject = realSubject; } public request(): void { if (this.checkAccess()) { this.realSubject.request(); this.logAccess(); } } private checkAccess(): boolean { console.log("Proxy: Checking access prior to firing a real request."); return true; } private logAccess(): void { console.log("Proxy: Logging the time of request."); } } function clientCode(subject: Subject) { subject.request(); } console.log("Client: Executing the client code with a real subject:"); const realSubject = new RealSubject(); clientCode(realSubject); console.log(""); console.log("Client: Executing the same client code with a proxy:"); const proxy = new Proxy(realSubject); clientCode(proxy); ``` 在这个示例中,`Subject` 接口定义了被代理对象(`RealSubject`)和代理对象(`Proxy`)的共同接口。`RealSubject` 实现了 `Subject` 接口,表示真正的对象。而 `Proxy` 类也实现了 `Subject` 接口,成为真正对象的代理。 `Proxy` 类包含一个指向 `RealSubject` 对象的引用,当客户端调用 `request()` 方法时,它会首先执行 `checkAccess()` 方法来检查是否有足够的权限来访问真正的对象。如果有,它会调用 `RealSubject` 对象的 `request()` 方法,并在访问结束后记录访问时间。 客户端代码可以使用 `RealSubject` 对象或 `Proxy` 对象来执行 `request()` 方法,因为它们都实现了 `Subject` 接口。但是,使用代理对象可以提供更多的控制和安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值