>>返回《C#常用设计模式》
1. 简介
- 定义
- 动态地给一个对象增加一些附属的职责。
- 装饰装饰,自然的理解就是在原有物品的基础上(不改变原有物品),增加一些别的东西,让它变得更令人满意。
- 类图
2. 示例
using System;
using
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
//client
class Program
{
static void Main()
{
Hero hero = new BigHero();
HeroShell s1 = new SpiderManShell(hero);
HeroShell s2 = new SupperManShell(s1);
s2.Attack();
Console.ReadKey();
}
}
//Component
public abstract class Hero
{
public abstract void Attack();
}
//Decorator
public abstract class HeroShell : Hero
{
private Hero _hero;
public HeroShell(Hero hero)
{
_hero = hero;
}
public override void Attack()
{
_hero.Attack();
}
}
//ConcreteDecoratorA
public class SpiderManShell : HeroShell
{
public SpiderManShell(Hero hero) : base(hero) { }
public override void Attack()
{
Console.WriteLine("织网");
Console.WriteLine("撒网");
base.Attack();
}
}
//ConcreteDecoratorB
public class SupperManShell : HeroShell
{
public SupperManShell(Hero hero) : base(hero) { }
public override void Attack()
{
Console.WriteLine("我飞");
Console.WriteLine("我裤衩反穿");
base.Attack();
}
}
//ConcreteComponent
public class BigHero : Hero
{
public override void Attack()
{
Console.WriteLine("我是破坏者,BigHero");
}
}
}
2.1. 框架中的例子
// 泛型集合基接口 component:组成
public interface IEnumerable<out T> : IEnumerable
{ }
// 只读集合接口 decorator:装饰器
public interface IReadOnlyCollection<out T> : IEnumerable<out T>
{ }
// 集合接口 decorator:装饰器
public interface ICollection<T> : IEnumerable<T>
{ }
// 列表接口 decorator:装饰器
public interface IList<T> : ICollection<T>, IEnumerable<T>
{ }
// 列表 concrete-implement: 具体实现
public class List<T> : ICollection<T>, IEnumerable<T>, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, IList
{ }
// 队列 concrete-implement: 具体实现
public class Queue<T> : IEnumerable<T>, IReadOnlyCollection<T>, ICollection
{ }
// 链表 concrete-implement: 具体实现
public class LinkedList<T> : ICollection<T>, IEnumerable<T>, IReadOnlyCollection<T>, IDeserializationCallback, ISerializable
{ }