首页 > 代码库 > 代理模式
代理模式
代理模式:为其它对象提供一个代理,以控制对这个对象的访问。
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
代理模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。