您的位置:首页 > 其它

设计模式笔记(四) —— 装饰模式

2008-10-27 15:19 225 查看
装饰模式(Decorator):装饰模式是为已有功能动态的添加更多功能的一种方式。

using System;

namespace StuDesignMode.Decorator

{

public class AbsCustomer

{

public string Name

{

get;

set;

}

public AbsCustomer() { }

public AbsCustomer(string name)

{

this.Name = name;

}

public virtual void Show()

{

Console.WriteLine("装扮的{0}", this.Name);

}

}

/// <summary>

/// 人

/// </summary>

public class Person:AbsCustomer

{

public Person(string name)

{

base.Name = name;

}

}

/// <summary>

/// 猫

/// </summary>

public class Cat : AbsCustomer

{

public Cat(string name)

{

base.Name = name;

}

}

/// <summary>

/// 服饰

/// </summary>

class Finery :AbsCustomer

{

private AbsCustomer _component;

/// <summary>

/// 打扮

/// </summary>

/// <param name="component"></param>

public void Decorate(AbsCustomer component)

{

this._component = component;

}

public override void Show()

{

if (this._component != null)

{

this._component.Show();

}

}

}

/// <summary>

/// T恤

/// </summary>

class TShirts : Finery

{

public override void Show()

{

Console.Write("大T恤 ");

base.Show();

}

}

/// <summary>

/// 垮裤

/// </summary>

class BigTrouser : Finery

{

public override void Show()

{

Console.Write("垮裤 ");

base.Show();

}

}

/// <summary>

/// 破球鞋

/// </summary>

class BrokenShoes : Finery

{

public override void Show()

{

Console.Write("破球鞋 ");

base.Show();

}

}

/// <summary>

/// 西装

/// </summary>

class Suit : Finery

{

public override void Show()

{

Console.Write("西装 ");

base.Show();

}

}

/// <summary>

/// 领带

/// </summary>

class Tie : Finery

{

public override void Show()

{

Console.Write("领带 ");

base.Show();

}

}

/// <summary>

/// 皮鞋

/// </summary>

class LeatherShoes : Finery

{

public override void Show()

{

Console.Write("皮鞋 ");

base.Show();

}

}

class ClientTest

{

static void Main(string[] args)

{

AbsCustomer xc = new Person("小菜");

Console.WriteLine("/n第一种装扮:");

TShirts ts = new TShirts();

BigTrouser bt = new BigTrouser();

BrokenShoes bs = new BrokenShoes();

//装饰过程

ts.Decorate(xc);

bt.Decorate(ts);

bs.Decorate(bt);

bs.Show();

Console.WriteLine("/n第二种装扮:");

Suit xz = new Suit();

Tie ld = new Tie();

LeatherShoes px = new LeatherShoes();

xz.Decorate(xc);

ld.Decorate(xz);

px.Decorate(ld);

px.Show();

//装扮花花

AbsCustomer huahua = new Cat("小猫花花");

ts.Decorate(huahua);

bt.Decorate(ts);

Console.WriteLine("/n小猫花花的装扮:");

bt.Show();

Console.WriteLine();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: