目录
- 定义
- UML
- 参与者
- 示例
定义:
代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。
UML:
参与者:
抽象主题(Subject)角色:
声明了代理主题和真实主题的公共接口,使任何需要真实主题的地方都能用代理主题代替.
具体主题(RealSubject)角色:
实现抽象主题角色的具体对象。
代理主题(Proxy)角色:
含有真实主题的引用,从而可以在任何时候操作真实主题,代理主题功过提供和真实主题相同的接口,使它可以随时代替真实主题.代理主题通过持有真实主题的引用,不但可以控制真实主题的创建或删除,可以在真实主题被调用前进行拦截,或在调用后进行某些操作.
示例:
代码using System; namespace DoFactory.GangOfFour.Proxy.Structural { /// <summary> /// MainApp startup class for Structural /// Proxy Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // Create proxy and request a service Proxy proxy = new Proxy(); proxy.Request(); // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Subject' abstract class /// </summary> abstract class Subject { public abstract void Request(); } /// <summary> /// The 'RealSubject' class /// </summary> class RealSubject : Subject { public override void Request() { Console.WriteLine("Called RealSubject.Request()"); } } /// <summary> /// The 'Proxy' class /// </summary> class Proxy : Subject { private RealSubject _realSubject; public override void Request() { // Use 'lazy initialization' if (_realSubject == null) { _realSubject = new RealSubject(); } _realSubject.Request(); } } }
Output
Called RealSubject.Request()
实际运用:
代码using System; namespace DoFactory.GangOfFour.Proxy.RealWorld { /// <summary> /// MainApp startup class for Real-World /// Proxy Design Pattern. /// </summary> class MainApp { /// <summary> /// Entry point into console application. /// </summary> static void Main() { // Create math proxy MathProxy proxy = new MathProxy(); // Do the math Console.WriteLine("4 + 2 = " + proxy.Add(4, 2)); Console.WriteLine("4 - 2 = " + proxy.Sub(4, 2)); Console.WriteLine("4 * 2 = " + proxy.Mul(4, 2)); Console.WriteLine("4 / 2 = " + proxy.Div(4, 2)); // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Subject interface /// </summary> public interface IMath { double Add(double x, double y); double Sub(double x, double y); double Mul(double x, double y); double Div(double x, double y); } /// <summary> /// The 'RealSubject' class /// </summary> class Math : IMath { public double Add(double x, double y) { return x + y; } public double Sub(double x, double y) { return x - y; } public double Mul(double x, double y) { return x * y; } public double Div(double x, double y) { return x / y; } } /// <summary> /// The 'Proxy Object' class /// </summary> class MathProxy : IMath { private Math _math = new Math(); public double Add(double x, double y) { return _math.Add(x, y); } public double Sub(double x, double y) { return _math.Sub(x, y); } public double Mul(double x, double y) { return _math.Mul(x, y); } public double Div(double x, double y) { return _math.Div(x, y); } } }
Output
4 + 2 = 6
4 - 2 = 2
4 * 2 = 8
4 / 2 = 2