DOTA版设计模式——代理
代理模式分为好多中,什么透明代理啦,远程代理啦,安全代理啦,本文介绍的是最基本的代理。
UML图:
真正的对象和代理对象均继承相同的接口,实例化代理对象时将真实对象传入,当操作代理对象时感觉像是在操作真正对象一样。像是代理对象把真正的对象包装后再在客户端处理。
internal interface ISubject
{
void Deal();
}
关键在代理类的构造函数中实现对真正对象的实例化,在类的成员方法中操作该真正对象的实例,具体见完整代码。注意真正的类是采用单件模式哦~~~~
完整代码:
UML图:
真正的对象和代理对象均继承相同的接口,实例化代理对象时将真实对象传入,当操作代理对象时感觉像是在操作真正对象一样。像是代理对象把真正的对象包装后再在客户端处理。
internal interface ISubject
{
void Deal();
}
关键在代理类的构造函数中实现对真正对象的实例化,在类的成员方法中操作该真正对象的实例,具体见完整代码。注意真正的类是采用单件模式哦~~~~
完整代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotaCommon;
namespace DotaPatternLibrary.Proxy
{
internal interface ISubject
{
void Deal();
}
public class Proxy : ISubject
{
#region ISubject 成员
public void Deal()
{
PrepareDeal();
subject.Deal();
CompleteDeal();
}
#endregion
private void PrepareDeal()
{
LandpyForm.Form.OutputResult("Proxy PrepareDeal");
}
private void CompleteDeal()
{
LandpyForm.Form.OutputResult("Proxy CompleteDeal");
}
private ISubject subject;
public Proxy(string input)
{
subject = RealSubject.Instance(input);
}
}
internal class RealSubject : ISubject
{
#region ISubject 成员
public void Deal()
{
LandpyForm.Form.OutputResult("RealSubject Deal" + "[" + input + "]");
}
#endregion
private static string input;
private static RealSubject realSubject;
private static object lockObj = new object();
public static RealSubject Instance(string inputValue)
{
input = inputValue;
lock (lockObj)
{
if (realSubject == null)
{
realSubject = new RealSubject();
}
return realSubject;
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotaCommon;
namespace DotaPatternLibrary.Proxy
{
internal interface ISubject
{
void Deal();
}
public class Proxy : ISubject
{
#region ISubject 成员
public void Deal()
{
PrepareDeal();
subject.Deal();
CompleteDeal();
}
#endregion
private void PrepareDeal()
{
LandpyForm.Form.OutputResult("Proxy PrepareDeal");
}
private void CompleteDeal()
{
LandpyForm.Form.OutputResult("Proxy CompleteDeal");
}
private ISubject subject;
public Proxy(string input)
{
subject = RealSubject.Instance(input);
}
}
internal class RealSubject : ISubject
{
#region ISubject 成员
public void Deal()
{
LandpyForm.Form.OutputResult("RealSubject Deal" + "[" + input + "]");
}
#endregion
private static string input;
private static RealSubject realSubject;
private static object lockObj = new object();
public static RealSubject Instance(string inputValue)
{
input = inputValue;
lock (lockObj)
{
if (realSubject == null)
{
realSubject = new RealSubject();
}
return realSubject;
}
}
}
}