代理模式

代理模式,为其他对象提供一种代理以控制对这个对象的访问。

结构图如下:

 

代码示例:

/// <summary>
/// 代理接口
/// </summary>
public interface IGiveGift
{
void GiveDoll();
void GiveFlower();
void GiveChocolate();
}

/// <summary>
/// 追求者
/// </summary>
public class Pursuiter : IGiveGift
{
public Girl girl;

public Pursuiter(Girl girl)
{
this.girl = girl;
}
public void GiveChocolate()
{
Console.WriteLine(girl.Name + "送你巧克力");
}

public void GiveDoll()
{
Console.WriteLine(girl.Name+"送你洋娃娃");
}

public void GiveFlower()
{
Console.WriteLine(girl.Name+"送你玫瑰花");
}

}

 

public class Girl
{
public string Name { get; set; }
}

 

public class Proxy : IGiveGift
{
Pursuiter pur;
public Proxy(Girl girl)
{
pur = new Pursuiter(girl);
}
public void GiveChocolate()
{
pur.GiveChocolate();
}

public void GiveDoll()
{
pur.GiveDoll();
}

public void GiveFlower()
{
pur.GiveFlower();
}
}

 

class Program
{
static void Main(string[] args)
{
Girl girl = new Girl() { Name = "小红" };
Proxy pro = new Proxy(girl);
pro.GiveChocolate();
pro.GiveDoll();
pro.GiveFlower();
Console.ReadKey();
}
}

 

追求者想追求小红,但不认识小红,只好通过代理。表面上看三个礼物(方法)是代理执行的,但实际上是追求者的。代理是真实对象的代表。

 

 

posted @ 2017-11-02 14:34  甘鑫丶  阅读(78)  评论(0)    收藏  举报