( Design Patterns ) Structural Design Patterns 2 -- Proxy Pattern

Definition

Provide a surrogate or placeholder for another object to control access to it. This pattern can be used when we don't want to access the resource or subject directly.

Components

  • Subject: Provides an interface that both actual and proxy class will implement. In this way the proxy can easily be used as a substitute for real subject.
  • Proxy: This class will be used by the applications and will expose the methods exposed by the Subject.
  • RealSubject: Real object that contains the actual logic to retrieve the data/functionality, which represented by the proxy.
( Design Patterns ) Structural Design Patterns 2 -- Proxy Pattern_第1张图片
Proxy Pattern UML

Code

public interface ISubject
{
    double Add(double x, double y);
    double Sub(double x, double y);
    double Mul(double x, double y);
    double Div(double x, double y);
}

public class Math : ISubject
{
    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; }
}

public class MathProxy : ISubject
{
    private Math _math;

    public MathProxy()
    {
        _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);
    }
}

public class ProxyPatternRunner : IPatterRunner
{
    public void RunPattern()
    {
        var proxy = new MathProxy();

        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));

        Console.ReadKey();
    }
}

Proxy Types

  • Remote proxies: Representing the object located remotely.

  • Virtual proxies: These proxies will provide some default behaviors if the real objects needs some time to perform these behaviors. Once the real object is done, these proxies push the actual data to the client.

  • Protection proxies: When an application does not have access to some resource then these proxies will talk to the objects.

Reference

Understanding and Implementing Proxy Pattern in C# - CodeProject

Design Patterns 2 of 3 - Structural Design Patterns - CodeProject

Head First Design Patterns - O'Reilly Media

你可能感兴趣的:(( Design Patterns ) Structural Design Patterns 2 -- Proxy Pattern)