装饰者模式

 

装饰者模式就是让一个类有更多的功能,多的话不说了,上具体的代码:

// 装饰者模式,就是让一个类有更多的功能

  

/// <summary>
/// 需要装饰的类(组件)
/// </summary>
public abstract class Phone
{
public virtual void Print()
{
Console.WriteLine("print");
}
}

 

// 具体的实现
public class ApplePhone:Phone
{
public void Print()
{
base.Print();
}
}

// 抽象修饰者
public abstract class Decrator : Phone
{
private Phone phone;

public Decrator(Phone p)
{
this.phone = p;
}

public override void Print()
{
if (phone !=null)
{
phone.Print();
}
}
}

// 具体修饰者
public class GuaJianDecrator : Decrator
{
public GuaJianDecrator(Phone p):base(p)
{

}

// 有自己的方法 也就是新的行为
public void AddGuaJia()
{
Console.WriteLine("AddGuajian");
}

public override void Print()
{
base.Print();

//添加自己的行为
AddGuaJia();
}

}

 

//使用情况
Phone p = new ApplePhone();

Decrator d = new GuaJianDecrator(p);

d.Print();

 

结果:

不仅完成了phone组件本身的任务,也实现了自己的需要装饰的功能,就是这么简单 !

posted on 2019-03-22 10:50  1老王  阅读(88)  评论(0编辑  收藏  举报