代理模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了代理模式相关的知识,希望对你有一定的参考价值。
代理模式:为其它对象提供一个代理,以控制对这个对象的访问。
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
以上是关于代理模式的主要内容,如果未能解决你的问题,请参考以下文章