Friday, June 7, 2013

Proxy design pattern in c#

Proxy: Provides a Placeholder for another object to control access to it.

 The proxy design pattern allows you to provide an interface to other objects by creating a wrapper class as the proxy. 
     * The wrapper class, which is the proxy, can add additional functionality to the object of interest without changing the object's code.

Below are some of the common examples in which the proxy pattern is used:

Adding security access to an existing object. The proxy will determine if the client can access the object of interest.
Simplifying the API of complex objects. 
     *** The proxy can provide a simple API so that the client code does not have to deal with the complexity of the object of interest.
     **** Providing interface for remote resources such as web service or REST resources.
*Coordinating expensive operations on remote resources by asking the remote resources to start the operation as soon as possible before accessing the resources.
***Adding a thread-safe feature to an existing class without changing the existing class's code.


     *** In short, the proxy is the object that is being called by the client to access the real object behind the scene.

class Program
    {
        static void Main(string[] args)
        {
            ICar car = new ProxyCar(new Driver(16));
            car.MoveCar();

            car = new ProxyCar(new Driver(20));
            car.MoveCar();

            Console.ReadKey();
        }
    }

    interface ICar
    {
        void MoveCar();
    }
    //the real object
    class Car : ICar
    {
        public void MoveCar()
        {
            Console.WriteLine("Car has been driven");
        }
    }
    class Driver
    {
        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
        public Driver(int age)
        {
            this._age = age;
        }        
    }

    //The Proxy
    class ProxyCar : ICar
    {
        private Driver driver;
        private ICar realCar;

        public ProxyCar(Driver driver)
        {
            this.driver = driver;
            realCar = new Car();
        }
        public void MoveCar()
        {
            if(driver.Age <=16)
                Console.WriteLine("Sorry the driver is too young to drive");
            else
                realCar.MoveCar();
        }

    }

No comments:

Post a Comment