設計模式-代理模式
阿新 • • 發佈:2018-05-09
設計模式 代理模式
public class house
{
public string name { get; set; }
public house(string _name)
{
this.name = _name;
}
}
public interface guke
{
void buyHouse();
}
public class xiaofeizhe : guke
{
house h;
public xiaofeizhe(house _h)
{
h = _h;
}
public void buyHouse()
{
Console.WriteLine(string.Format("我要買名字為{0}的房子",h.name));
}
}
public class proxy : guke
{
house h;
xiaofeizhe x;
public proxy(house _h)
{
this.h = _h;
}
public void buyHouse()
{
if(x==null)
x = new xiaofeizhe(h);
x.buyHouse();
}
}
前端:
static void Main(string[] args)
{
house h = new house("盤古大廈");
proxy p = new proxy(h);
p.buyHouse();
Console.ReadLine();
}
總結:如果不使用代理類·直接調用對象,那麽當需求有變更時,就需要改變該對象,違反了開閉原則,使用代理類的話,就沒有這種問題出現。
特點:代理類中引入被代理的對象,和裝飾模式有一點類似,都是引入第三方對象(但是裝飾模式主要是擴展對象的行為、屬性)。
好處:1、結構清晰,2、保護了被代理對象,3、高擴展
設計模式-代理模式