Design Pattern in .NET 101 - Proxy Pattern (Structural Pattern)
By admin on Jan 8, 2008 in .NET, Programming, Structural
Proxy Pattern provides a surrogate or placeholder for another object to control access to it.
E.g.
I defined a IGreeting interface
using System;
using System.Collections.Generic;
using System.Text;
namespace ProxyPattern
{
interface IGreeting
{
void SayHello();
}
}
Greeting implements IGreeting
using System;
using System.Collections.Generic;
using System.Text;
namespace ProxyPattern
{
class Greeting: IGreeting
{
private string hello;
public Greeting(String hello)
{
this.hello = hello;
}
public void SayHello()
{
Console.WriteLine(hello);
}
}
}
GreetingProxy is used to access Greeting
using System;
using System.Collections.Generic;
using System.Text;
namespace ProxyPattern
{
class GreetingProxy
{
private Greeting greeting;
public GreetingProxy(string hello)
{
greeting = new Greeting(hello);
}
public void SayHello()
{
// Can perform extra logic here
greeting.SayHello();
}
}
}
To test it
using System;
using System.Collections.Generic;
using System.Text;
namespace ProxyPattern
{
class Program
{
static void Main(string[] args)
{
GreetingProxy proxy1 = new GreetingProxy("hello");
GreetingProxy proxy2 = new GreetingProxy("bonjour");
proxy1.SayHello();
proxy2.SayHello();
Console.ReadLine();
}
}
}
