首页 > 代码库 > 代理模式

代理模式

代理模式:为其它对象提供一个代理,以控制对这个对象的访问。

 

UML类图

技术分享

抽象类或者接口:

abstract class Subject
{
    public abstract void Request();
}

实现类:

class ReadSubject : Subject
{
    public override void Request()
    {
        Console.WriteLine("真实的请求");
    }
}

代理类:

class Proxy:Subject
{
    ReadSubject readSubject;
    public override void Request()
    {
        if (readSubject == null)
        {
            readSubject = new ReadSubject();
        }
        readSubject.Request();
    }
}

客户端:

static void Main(string[] args)
{
    Proxy proxy = new Proxy();
    proxy.Request();

    Console.Read();
}

运行结果:

技术分享

程序结构:

技术分享

-----------------------------------------

运算接口:

public interface IMath
{
    double Add(double a, double b);
    double Sub(double a, double b);
    double Mul(double a, double b);
    double Div(double a, double b);
}

实现类:

public class Math : IMath
{
    public double Add(double a, double b)
    {
        return a + b;
    }

    public double Div(double a, double b)
    {
        return a - b;
    }

    public double Mul(double a, double b)
    {
        return a * b;
    }

    public double Sub(double a, double b)
    {
        return a / b;
    }
}

代理类:

public class MathProxy : MarshalByRefObject, IMath
{
    private Math math;
    public MathProxy()
    {
        if (math == null)
        {
            math = new Math();
        }
    }

    //public MathProxy()
    //{
    //    AppDomain ad = System.AppDomain.CreateDomain("MathDomain", null, null);
    //    ObjectHandle o = ad.CreateInstance("Proxy_RealWorld", "Math", false, System.Reflection.BindingFlags.CreateInstance, null, null, null, null, null);
    //    math = (Math)o.Unwrap();
    //}

    public double Add(double a, double b)
    {
        return math.Add(a, b);
    }

    public double Div(double a, double b)
    {
        return math.Div(a, b);
    }

    public double Mul(double a, double b)
    {
        return math.Mul(a, b);
    }

    public double Sub(double a, double b)
    {
        return math.Sub(a, b);
    }
}

客户端:

static void Main(string[] args)
{
    MathProxy p = new MathProxy();
    Console.WriteLine(p.Add(4,2));
    Console.WriteLine(p.Sub(4, 2));
    Console.WriteLine(p.Mul(4, 2));
    Console.WriteLine(p.Div(4, 2));

    Console.ReadKey();
}

运行结果:

技术分享

 

 

参考文章:

  http://www.cnblogs.com/zhenyulu/articles/48128.html

代理模式