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:

Arjun PanwarPosted Apr 23, 2012, 12:40 AM
Hi, What is wrapper patterns in C#?
Arjun PanwarPosted Apr 23, 2012, 12:39 AM
Hi, What is wrapper patterns in C#?