以下示例性代碼實現了代理模式:
// Proxy pattern -- Structural example
using System;
// "Subject"
abstract class Subject
{
// Methods
abstract public void Request();
}
// "RealSubject"
class RealSubject : Subject
{
// Methods
override public void Request()
{
Console.WriteLine("Called RealSubject.Request()");
}
}
// "Proxy"
class Proxy : Subject
{
// FIElds
RealSubject realSubject;
// Methods
override public void Request()
{
// Uses "lazy initialization"
if( realSubject == null )
realSubject = new RealSubject();
preRequest();
realSubject.Request();
postRequest();
}
public void preRequest()
{ Console.WriteLine("PreRequest."); }
public void postRequest()
{ Console.WriteLine("PostRequest."); }
}
/**//// <summary>
/// ClIEnt test
/// </summary>
public class ClIEnt
{
public static void Main( string[] args )
{
// Create proxy and request a service
Proxy p = new Proxy();
p.Request();
}
}