Proxy Pattern

 

Comments

 

Adds a layer on-top of the interface derived class i.e. I call method to do something using no proxy does as expected using proxy can add extra functions (like a top-layer), why, provides no amendments to existing code.

 

Code

 

namespace IVSR.DesignPattern.Proxy
{
    interface ICar
    {
        void DriveCar();
    }

    //Real Object 
    public class Car : ICar
    {
        public void DriveCar()
        {
            Console.WriteLine("Car has been driven!");
        }
    }

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

        public ProxyCar(Driver driver)
        {
            this.driver = driver;
            realCar = new Car();
        }

        public void DriveCar()
        {
            if (driver.Age <= 16)
                Console.WriteLine("Sorry, the driver is too young to drive.");
            else
                realCar.DriveCar();
         }
     }

    public class Driver
    {
        public int Age { get; set; }

        public Driver(int age)
        {
            this.Age = age;
        }
    }

    //How to use above Proxy class? 
    private void btnProxy_Click(object sender, EventArgs e)
    {
        ICar car = new ProxyCar(new Driver(16));
        car.DriveCar();

        car = new ProxyCar(new Driver(25));
        car.DriveCar();
    }
}

Output

 

Sorry, the driver is too young to drive.

Car has been driven!