Design Patterns: Proxy

The proxy design pattern is a layer that prevents you from instantiating heavy objects that will not be needed at a certain time.

The proxy pattern could be used to:

  • prevent loading unnecessary resources
  • access real data in a remote location
  • prevent control from accessing non-declared members/methods

One example of the proxy structure could be the following:


I can have a proxy to access a store, if the store is closed it shouldn't even bother loading unnecessary resources.

  1. public interface IStore  
  2. {  
  3.     void ListItems();  
  4. }  
  5.    
  6. public class ProxyStore : IStore  
  7. {  
  8.     private RealStore realStore;  
  9.    
  10.     public void ListItems()  
  11.     {  
  12.         if (DateTime.Now.Hour >= 6 && DateTime.Now.Hour <= 10)  
  13.         {  
  14.             if (realStore == null)  
  15.             {  
  16.                 realStore = new RealStore();  
  17.             }  
  18.    
  19.             realStore.ListItems();  
  20.         }  
  21.         else  
  22.         {  
  23.             Console.WriteLine("We're closed!");  
  24.         }  
  25.     }  
  26. }  
  27. public class RealStore : IStore  
  28. {  
  29.     public void ListItems()  
  30.     {  
  31.         Console.WriteLine("Heavy graphics Weapon 1");  
  32.         Console.WriteLine("Heavy graphics Weapon 2");  
  33.         Console.WriteLine("Heavy graphics Weapon 3");  
  34.         Console.WriteLine("Heavy graphics Weapon 4");  
  35.         Console.WriteLine("Heavy graphics Weapon 5");  
  36.     }  
  37. }  

This example is something we can see in Assassins's Creed where this pattern might have been used. In an early game there is a shop that has many unavailable options. Instead of loading all the resources required for the items it uses a proxy saying there is nothing available, so it saves many resources.


Similar Articles