代理模式(Proxy pattern) 转 1. 代理模式代理模式的作用是:为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个客户不想或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。代理模式一般涉及到三个角色:抽象角色:声明真实对象和代理对象的共同接口;代理角色:代理对象角色内部含有对真实对象的引用,从而可以操作真实对象,同时代理对象提供与真实对象相同的接口以便在任何时刻都能代替真实对象。同时,代理对象可以在执行真实对象操作时,附加其他的操作,相当于对真实对象进行封装。真实角色:代理角色所代表的真实对象,是我们最终要引用的对象。
using System;
namespace MyApp
{
class Program
{
static void Main()
{
ReceivePerson mother = new ReceivePerson("Liu");
SendPerson son1 = new SendPerson("Xufei96", "a double of pictures", mother);
SendPerson son2 = new SendPerson("Xuyang","a pair of shoes",mother);
PostPerson postPerson = new PostPerson(son1);
postPerson.PostMethod();
postPerson = new PostPerson(son2);
postPerson.PostMethod();
Console.ReadKey();
}
}
class Person
{
public Person(string name)
{
Name = name;
}
public string Name { get; set; }
}
interface Post
{
void PostMethod();
}
class PostPerson:Post
{
public PostPerson(SendPerson sendPerson)
{
this.sendPerson = sendPerson;
}
private SendPerson sendPerson;
public void PostMethod()
{
if (sendPerson != null)
{
sendPerson.PostMethod();
}
}
}
class ReceivePerson:Person
{
public ReceivePerson(string name):base(name)
{
}
}
class SendPerson : Person, Post
{
private string packet { get; set; }
private ReceivePerson TheReceivePerson { get; set; }
public SendPerson(string sendPersonName, string flowerName, ReceivePerson theReceivePerson):base(sendPersonName)
{
packet = flowerName;
TheReceivePerson = theReceivePerson;
}
public void PostMethod()
{
Console.WriteLine("{0} sends {1} to {2}.", Name, packet,TheReceivePerson.Name);
}
}
}
168万+

被折叠的 条评论
为什么被折叠?



