為其他對象提供代理以控制對該對象的訪問。
代理模式極常用:降低使用複雜度、提升友好度、提高效率。生活中:明星經紀人(節省明星時間)、保險代理人(降低投保複雜度)。開發中:網站透過 .NET Remoting 訪問帳號服務,調試時希望直接引用 DLL 實例化,正式環境走遠程呼叫。引入 Proxy 封裝環境切換與遠程呼叫細節。
using System;
using System.Collections.Generic;
using System.Text;
namespace ProxyExample
{
class Program
{
static void Main(string[] args)
{
AccountProxy ap = new AccountProxy();
ap.Register();
}
}
interface IAccount { void Register(); }
class Account : IAccount
{
public void Register() { System.Threading.Thread.Sleep(1000); Console.WriteLine("Done"); }
}
class AccountProxy : IAccount
{
readonly bool isDebug = true;
IAccount account;
public AccountProxy()
{
if (isDebug) account = new Account();
else account = (IAccount)Activator.GetObject(typeof(IAccount), "uri");
}
public void Register()
{
Console.WriteLine("Please wait...");
account.Register();
}
}
}