>>返回《C#常用設(shè)計(jì)模式》
1. 簡介
- 定義
- 動(dòng)態(tài)地給一個(gè)對(duì)象增加一些附屬的職責(zé)。
- 裝飾裝飾,,自然的理解就是在原有物品的基礎(chǔ)上(不改變?cè)形锲?/strong>),,增加一些別的東西,讓它變得更令人滿意,。
- 類圖
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("織網(wǎng)");
Console.WriteLine("撒網(wǎng)");
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: 具體實(shí)現(xiàn)
public class List<T> : ICollection<T>, IEnumerable<T>, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, IList
{ }
// 隊(duì)列 concrete-implement: 具體實(shí)現(xiàn)
public class Queue<T> : IEnumerable<T>, IReadOnlyCollection<T>, ICollection
{ }
// 鏈表 concrete-implement: 具體實(shí)現(xiàn)
public class LinkedList<T> : ICollection<T>, IEnumerable<T>, IReadOnlyCollection<T>, IDeserializationCallback, ISerializable
{ }
|