Proxy Pattern Code Review

Use the Proxy Pattern

Code Download

  • Download Description:proxy pattern download
  • .NET Framework:3.5
  • .NET Language:C#
  • Date Published:2009-07-01
  • Download Size:48 KB

Code Walkthrough

Define the IPicture interface represents the "blueprint" for a set of complex classes (objects).

class PictureAccessor { public interface IPicture { System.Drawing.Image getImage(); }

The LoadPicture class (object) inherits from the IPicture interface and represents one type of "complex" class.

private class LoadPicture : IPicture { public System.Drawing.Image getImage() { return new System.Drawing.Bitmap("loading.jpg"); } }

The FinalPicture class (object) inherits from the IPicture interface and represents another type of "complex" class.

private class FinalPicture : IPicture { public System.Drawing.Image getImage() { return new System.Drawing.Bitmap("blueskysailboat.jpg"); } }

The PictureProxy class manages the creation of the "complex" classes and provides a single interface for the client.

public class PictureProxy : IPicture { private Boolean loaded = false; private Boolean authenticated = false;
private IPicture pic = null; private System.Threading.Timer timer = null;
public PictureProxy() { try { this.loaded = false; this.authenticated = false; this.timer = new System.Threading.Timer(new System.Threading.TimerCallback(timer_CallBack), this, 5000, 0); } catch { throw; } }
public System.Drawing.Image getImage() { if (authenticated) { if (this.pic == null) { if (this.loaded) { this.pic = new FinalPicture(); } else { this.pic = new LoadPicture(); } } return pic.getImage(); } else { return null; } } public void Authenticate(String password) { if (String.Compare(password, "Abracadabra") == 0) { this.authenticated = true; } else { this.authenticated = false; } } private void timer_CallBack(Object obj) { try { this.loaded = true; this.pic = null; this.timer.Dispose(); } catch { throw; } } } }