Home
Gallery
GuestBook
SourceCode
Contact

Design Patterns for Dummies. The Proxy Pattern

Posted in Design Patterns
This post has been read 1816 times

This is the second post in a series of post on Design patterns. Presently we are going through the structural patterns. In my previous post I had discussed about the Decorator Pattern. I will be writing about the proxy pattern today.

Proxy patterns is all about creating small objects which in turn are used in creating and accessing more complex objects.

    1 public class Vehicle

    2 {

    3     public string Name { get; set; }

    4     public string Model { get; set; }

    5 }

    6 

    7 public interface IGear

    8 {

    9     void GearUp( Vehicle v );

   10     void GearDown( Vehicle v );

   11 }

   12 

   13 public class RunVehicle : IGear

   14 {

   15     public void GearUp( Vehicle v )

   16     {

   17         Console.WriteLine( "Going one gear up : {0}", v.Name );

   18     }

   19 

   20     public void GearDown( Vehicle v )

   21     {

   22         Console.WriteLine( "Going one gear down : {0}", v.Name );

   23     }

   24 }

   25 

   26 public class VehicleProxy : IGear

   27 {

   28     private RunVehicle _runVehicle;

   29 

   30     public VehicleProxy()

   31     {

   32         _runVehicle = new RunVehicle();

   33     }

   34 

   35     public void GearUp( Vehicle v )

   36     {

   37         _runVehicle.GearUp( v );

   38     }

   39 

   40     public void GearDown( Vehicle v )

   41     {

   42         _runVehicle.GearDown( v );

   43     }

   44 }

   45 

   46 public class Program

   47 {

   48     public static void Main()

   49     {

   50         VehicleProxy proxy = new VehicleProxy();

   51 

   52         proxy.GearUp( new Vehicle { Name = "Vehicle1", Model = "Model1" } );

   53         //Output : Going one gear up : Vehicle1

   54         proxy.GearDown( new Vehicle { Name = "Vehicle1", Model = "Model1" } );

   55         //Output : Going one gear down : Vehicle1

   56 

   57         Console.ReadLine();

   58     }

   59 }

Proxies act as frontend to classes that are complex or rather heavy in their operation. Proxies are similar to decorators in the sense that they both delegate requests to another object, however the proxy relationship is well know at design time for objects where as in decorators they are added dynamically. Proxies are to be used when, creation of objects of any class is expensive or when we need to access a remote object, or when we need to perform some action when an object is called or rather creation  of objects only when an operation is called.

In my next post I will be discussing about the Bridge pattern.




Name:
E-mail:
Website:
Comment:
 
Anti Bot Image:

Insert Cancel


Subscribe

Random Photo

My Tweets


Top Posts

Source Code

The source code to this site is open-source. You can download the code from here.

Categories


Recent Blogs


Archives


Blogroll