《大话设计模式》读书笔记4 装饰模式

装饰模式(Decorator):动态地给一个对象增加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

装饰模式结构图:


装饰模式实现代码:

abstract class Component
{
	public abstract void Operation();
}

class ConcretComponent:Component
{
	public override void Operation()
	{
		Console.WriteLine("具体对象的操作");
		
	}
}

abstract class Decorator:Component
{
	protected Component component;
	
	public void SetComponent(Component component)
	{
		this.component=component;
	}
	public override void Operation()
	{
		if(component!=null)
		{
			component.Operation();
		}
	}
}

class ConcretDecoratorA:Decorator
{
	private string addedState;
	
	public override void Operation()
	{
		base.Operation();
		addedState="New State";
		Console.WriteLine("具体装饰对象A的操作");
	}
}

class ConcretDecoratorB:Decorator
{
	public override void Operation()
	{
		base.Operation();
		AddedBehaviour();
		Console.WriteLine("具体装饰对象B的操作");
	}
	
	private void AddedBehaviour()
	{
		
	}
}

static void Main(string[] args)
{
	ConcretComponent c=new ConcretComponent();
	ConcretDecoratorA d1=new ConcretDecoratorA();
	ConcretDecoratorB d2=new ConcretDecoratorB();
	
	d1.SetComponent(c);
	d2.SetComponent(d1);
	d2.Operation();
	
	Console.Read();
	
}



posted @ 2016-02-20 11:20  牧羊少年10号  阅读(92)  评论(0编辑  收藏  举报