Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Design & Architecture » Wrapper Patterns in C#, Part II: The Proxy Pattern

Wrapper Patterns in C#, Part II: The Proxy Pattern

Did you ever wish for a superhuman power to be impervious to bullets or travel outside your body? How about the superpower to be able to breathe underwater or fly? Or how about a changing the way you look so you can disguise yourself as anyone, or anything? In this series of four articles, we will travel down the C# wrapper rabbit hole and see how it is all possible with some patterns: Proxy, Decorator, and Adapter.

Author Rank :
Page Views : 21253
Downloads : 287
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ProxySample.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Did you ever wish for a superhuman power to be impervious to bullets or travel outside your body? How about the superpower to be able to breathe underwater or fly?   Or how about a changing the way you look so you can disguise yourself as anyone, or anything?  In this series of four articles, we will travel down the C# rabbit hole and see how it is all possible with some wrapper patterns: Proxy, Decorator, and Adapter. 

Part II. The Proxy

When we use our wrapper powers to have wrappers make objects appear where they are not or shield a wrapped object, we are really talking about the GOF Proxy pattern.  Let us first look at how our newly discovered wrapper power can stop bullets and give us the ability to travel outside our bodies.

The force shield wrapper (protection by proxy)

Let's say we have a contract for a person IDude.  All objects that implement the IDude interface have a name and can get shot.

public interface IDude

{

          string Name { get; set; }

          void GotShot(string typeOfGun);

}

Here is a NormalDude.  If any NormalDude gets shot, they get hurt.

public class NormalDude: IDude

{

          private string m_Name = string.Empty;

          private bool m_IsHurt = false;

          public string Name

          {

          get{ return m_Name;}

                    set{ m_Name = value; }

          }

          public void GotShot(string typeOfGun)

          {

                    m_IsHurt = true;

                    Console.WriteLine(m_Name + " got shot by a " + typeOfGun + " gun.");

          }

          public override string ToString()

          {

                    StringBuilder result = new StringBuilder();

result.Append(m_Name);

          if(m_IsHurt) { result.Append(" is hurt"); }

                    else { result.Append(" is as healthy as a clam"); }

          return result.ToString();

          }

}

And here is a wrapper for our NormalDude: a SuperDude.  If a SuperDude gets shot, he acts as a shield for the NormalDude he wraps.  Any NormalDude wrapped in a SuperDude can't get hurt by getting shot.  This is an example the Proxy pattern because we are limiting access to the wrapped object.

public class SuperDude : IDude

{

          private IDude m_dude;

          public SuperDude(IDude dude)

          {

                    m_dude = dude;

          }

          #region IDude Members

          public string Name

          {

                    get { return "Super" + m_dude.Name; }

                    set { m_dude.Name = value; }

          }

          public void GotShot(string typeOfGun)

          {

                    StringBuilder result = new StringBuilder();

                    result.Append(this.Name).Append(" got shot by a ").Append(typeOfGun);

                    result.Append(" gun but it bounced off!!  \nYou can't hurt ").Append(this.Name);

                    result.Append("\n\n");

                    Console.WriteLine(result.ToString());

                    // NOTICE: THE GotShot() METHOD WAS NOT CALLED ON THE WRAPPED OBJECT

          }

          #endregion

          public override string ToString()

          {

                    StringBuilder result = new StringBuilder();

                    result.Append(Name).Append(" can't get hurt!");

                    result.Append(" (").Append(Name).Append(" is a super-hero proxy, you know).\n");

                    return result.ToString();

          }

}

Here's what happens when the bad-guys come along:

IDude Joe = new NormalDude();
Joe.Name = "Average Joe";
IDude Clark = new NormalDude(); // MILD MANNERED CLARK (You know the one...)
Clark.Name = "Clark";
Clark =
new SuperDude(Clark); // HERE IS WHERE WE WRAP Clark (He puts the suit on)
Console.WriteLine("HERE COME THE BAD-GUYS -- BULLETS ARE FLYING EVERYWHERE\n\n");
Joe.GotShot("Pea Shooter");
Clark.GotShot("Bazooka");
Console.WriteLine(Joe.ToString());
Console.WriteLine(Clark.ToString());

Here are the results:

Projection (interaction by proxy)

If use a wrapper to remotely view and interact with things, then it is a remote proxy.  Let's look at another example.  We can also use a proxy as a stand-in for the real object it is wrapping.

Let's say we have an interface that defines perceiving and changing a string.

public interface IInteractor

{

          void Percieve(string percievedThing);

          void Change(ref string perceivedThing);

}

And a Me class that implements the interface:

class Me: IInteractor

{

          private string m_LookingAt;

          private string m_ChangeTo;

          public string ChangeTo

          {

                    get { return m_ChangeTo; }

                    set { m_ChangeTo = value; }

          }

          #region IInteractor Members

          public void Percieve(string percievedThing)

          {

                    m_LookingAt= percievedThing;

          }

          public void Change(ref string perceivedThing)

          {

                    Console.WriteLine("I'm changing " + perceivedThing + " to a " + m_ChangeTo);

                    perceivedThing = m_LookingAt = m_ChangeTo;

          }

          #endregion

          public override string ToString()

          {

                    return "I'm looking at a " + m_LookingAt;

          }

}

A house class in which something can be changed:

class House

{

          private string m_thing = "vase";

          public void LookAtThing(IInteractor person)

          {

                    person.Percieve(m_thing);

          }

          public void ChangeThing(IInteractor person)

          {

                    person.Change(ref m_thing);

          }

          public override string ToString()

          {

                    return "This house has a " + m_thing;

          }

}

And a proxy for the Me class:

class MeProxy : IInteractor

{

          private Me m_wrappedObject;

          public MeProxy(Me wrappedObject)

          {

                    m_wrappedObject = wrappedObject;

          }

          #region IInteractor Members

          public void Percieve(string percievedThing)

          {

                    Console.WriteLine("Perception by Proxy");

                    m_wrappedObject.Percieve(percievedThing);

          }

          public void Change(ref string perceivedThing)

          {

                    Console.WriteLine("Change by Proxy");

                    m_wrappedObject.Change(ref perceivedThing);

          }

          #endregion

          public override string ToString()

          {

                    return "I'm an apparition.  The real me says:" + m_wrappedObject.ToString();

          }

}

Here's the story.  Joe has a favorite vase at his house.  We thought it would be funny to put a duck in place of the vase.  When Joe found out, he was pretty angry so we use our secret proxy power to send an apparition into his house and change the duck into a bag of money (so he can buy a new vase).

IDude Joe = new NormalDude();
Joe.Name = "Average Joe";
Me Matt =
new Me();
House JoesHouse =
new House();
JoesHouse.LookAtThing(Matt);
// I'm looking at what's in JoesHouse
Console.WriteLine(Matt.ToString());
Console.WriteLine(JoesHouse.ToString());
// I'll change whatever I find to a duck
Matt.ChangeTo = "duck";
JoesHouse.ChangeThing(Matt);
Console.WriteLine(Matt.ToString());
Console.WriteLine(JoesHouse.ToString());
Console.WriteLine("\nJoe is upset -- his vase is a duck.\n----------------------------------\n\n");
// Because Joe is upset, we'll use our superpower to change the duck to a bag-o-money
// We dont' want to go in ourselves, so we'll send the proxy.
MeProxy Apparition = new MeProxy(Matt);
Matt.ChangeTo = "bag-o-money";
JoesHouse.ChangeThing(Apparition);
Console.WriteLine(Matt.ToString());
Console.WriteLine(JoesHouse.ToString());
Console.WriteLine(Apparition.ToString());

This example demonstrates how we can use the proxy pattern to interact with things through a proxy by passing method calls through the proxy.

Next article we'll look at the powers a decorator can give us.

Until then

-Only use your powers for good.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Matthew Cochran
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.