老婆有一件蓝色的裙子和一件粉色的裙子, 不管怎么穿,她还是原来的老婆。 但是在软件里就不一定了, 如果把老婆比作一个class的话, 有一种做法是会因为增加了两个新的Property而继承出两个子类:

"穿裙子的老婆, 穿粉色上衣的老婆".

你这样弄出两个子类也没什么不对, 问题是当MM的有上百件服装的时候,就会产生上百个子类,这个不好,将来万一父类一变化,下面上百个子类都要一个个地去修改,太乱了。

有一个更合理的方式来解决这个"老婆的装饰问题"。我们的要求是:
      老婆不能因为穿上了不同的衣服而从本质上改变她这个人,(逻辑上说, 不要又来一个"白马非马")。

根据按上面的要求, 我们可以写出以下的代码:


using System;
using System.Collections.Generic;
using System.Text; public class Feifei
{
private string _myclothes;
public string MyClothes
{
get{return _myclothes;}
set{_myclothes = value;}
}
} public class BlueSkirt:Feifei
{
private Feifei _f;
private StringBuilder _myclothes = new StringBuilder(); public BlueSkirt(Feifei f)
{
_f = f;
} public string MyClothes
{
get
{
_myclothes.Append(_f.MyClothes);
_myclothes.Append("and a piece of blue skirt"); return _myclothes.ToString();
}
set{;} }
} public class PinkSkirt:Feifei
{
private Feifei _f;
private StringBuilder _myclothes = new StringBuilder(); public PinkSkirt(Feifei f)
{
_f = f;
} public string MyClothes
{
get
{
_myclothes.Append(_f.MyClothes);
_myclothes.Append("and a piece of pink skirt"); return _myclothes.ToString();
}
set{;} }
} public class MyClass
{
public static void Main()
{
//老婆穿白色的鞋子出场
Feifei f1 = new Feifei();
f1.MyClothes = "I have white shoes,"; //换上蓝色的裙子
BlueSkirt f2 = new BlueSkirt(f1);
Console.WriteLine(f2.MyClothes); //换上粉色的裙子
PinkSkirt f3 = new PinkSkirt(f1);
Console.WriteLine(f3.MyClothes); Console.Read();
} }
好,我们来看一下结果。
小故事学设计模式之Decorate: (二)老婆的新衣服-LMLPHP
 
以上就是Decorate模式的个人理解。
 
谢谢!
05-11 13:59