BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 1.1+

Proxy Design Pattern

The proxy pattern is a design pattern that creates a surrogate, or placeholder class. Proxy instances accept requests from client objects, pass them to the underlying object and return the results. Proxies can improve efficiency and enhance functionality.

Example Proxy

Earlier in this article I mentioned that the proxy design pattern could be used to provide a cache proxy. In this case, a complex, long-running calculation would only be executed once. Subsequent requests for the calculation's result would be returned from the proxy without accessing the underlying object.

In the following code, a cache proxy is used in this manner. To simplify the sample, the calculation performed is a multiplication of all of the numbers between one and ten. To emulate a slow process, the thread is paused for half a second between each multiplication. The underlying calculation is only performed if the NumberMultiplier object has not yet been created.

public abstract class CalculatorBase
{
    public abstract int Calculate();
}


public class NumberMultiplier : CalculatorBase
{
    public override int Calculate()
    {
        int result = 1;

        for (int i = 2; i <= 10; i++)
        {
            result *= i;
            Thread.Sleep(500);
        }

        return result;
    }
}


public class NumberMultiplierProxy : CalculatorBase
{
    private NumberMultiplier _realNumberMultiplier;
    private int _cachedValue;

    public override int Calculate()
    {
        if (_realNumberMultiplier == null)
        {
            _realNumberMultiplier = new NumberMultiplier();
            _cachedValue = _realNumberMultiplier.Calculate();
        }

        return _cachedValue;
    }
}

Testing the Proxy

To test the proxy we can use a new console application. Add the code shown below to the Main method then execute the program. The Calculate method of the proxy will be executed ten times. On the first attempt, a NumberMultiplier object is created and used to perform the calculation. This is slow due to the Thread.Sleep commands. The remaining nine calculation requests provide results very quickly because the cached value is used instead.

CalculatorBase cb = new NumberMultiplierProxy();

for (int i = 0; i < 10; i++)
{
    Console.WriteLine(cb.Calculate());
}
11 January 2009