1. 定义
为其他对象提供一种代理以控制对这个对象的访问。2. UML 类图
3. 结构代码
// Proxy pattern -- Structural example
|
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()
|
4. 实例代码
// Proxy pattern -- Real World example
|
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 |
该文章来自:http://www.dofactory.com/Patterns/PatternProxy.aspx