![](https://i-blog.csdnimg.cn/blog_migrate/6d592cfa06019f8c012aac371be6b1fe.png)
//给对象动态添加职责
abstract class Component
{
public abstract void Operation();
}
class ConcreteComponent: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();
}
}
}
//装饰A
class ConcreteDecoratorA:Decorator
{
private string addedState;
public override void Operation()
{
base.Operation();
//相当于对原Component进行了装饰
addedState = "New State";
Console.WriteLine("具体装饰对象A的操作");
}
}
//装饰B
class ConcreteDecoratorB:Decorator
{
public override void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine("具体装饰对象B的操作");
}
private void AddedBehavior()
{
Console.WriteLine("B执行行为");
}
}
//主函数
class Program
{
static void Main(string[] args)
{
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
d1.SetComponent(c);
d2.SetComponent(d1);
d2.Operation();
}
}
//要装饰的人
class Person
{
private string name;
public Person() { }
public Person(string name)
{
this.name = name;
}
public virtual void Show()
{
Console.Write($" {name}");
}
}
//服装抽象类
class Finery:Person
{
protected Person component;
public void Decorate(Person component)
{
this.component = component;
}
public override void Show()
{
if(component!=null)
{
component.Show();
}
}
}
//T恤
class Tshirt:Finery
{
public override void Show()
{
Console.Write(" T恤");
base.Show();
}
}
//大垮裤
class BigTrouser:Finery
{
public override void Show()
{
Console.Write("垮裤");
base.Show();
}
}
//主函数
class Program
{
static void Main(string[] args)
{
Person xc = new Person("小菜");
Tshirt tshirt = new Tshirt();
BigTrouser bigTrouser = new BigTrouser();
tshirt.Decorate(xc);
bigTrouser.Decorate(tshirt);
bigTrouser.Show();
}
}
- 装饰模式是为已有功能动态地添加更多功能的一种方式,把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,当需要执行特殊行为时,就可以在运行时根据需要有选择地、按顺序的使用装饰功能包装对象。
(完)