C#设计模式:19.代理模式 u3d学习总结笔记本

代理模式(Proxy Pattern)

提供了对目标对象另外的访问方式,即通过代理对象访问目标对象,这样可以在目标对象实现的基础上,增强额外的功能操作,即扩展目标对象的功能。
如果需改修改原来的类型功能方法,可以通过代理的方式来扩展该方法。

使用场景:想在访问一个类时做一些控制。

优点:

 1、职责清晰。

 2、高扩展性。

 3、智能化。

缺点:

 1、由于在客户端和真实主题之间增加了代理对象,因此有些类型的代理模式可能会造成请求的处理速度变慢。

 2、实现代理模式需要额外的工作,有些代理模式的实现非常复杂。

抽象功能类:

//抽象功能类
public abstract class Ab_Function
{
    public abstract int myAdd(int a, int b);
}

具体功能类:

//具体功能类
public class MyMathf : Ab_Function
{
    //实现功能
    public override int myAdd(int a, int b)
    {
        return a + b;
    }
}

代理类:

//代理类
public class Proxy : Ab_Function
{
    MyMathf mathf;

    //调用原功能
    public override int myAdd(int a, int b)
    {
        if (mathf == null) mathf = new MyMathf();

        return myPrint(mathf.myAdd(a, b));
    }

    //外加功能:代理打印
    public int myPrint(int a)
    {
        Debug.Log("代理打印:相加得:" + a);
        return a;
    }
}

运行测试:

结果:

猜你喜欢

转载自blog.csdn.net/qq_40346899/article/details/109315045