Decorator(装饰)模式

Posted on 2008-11-08 13:26 Herbert 阅读(710) 评论(0)  编辑 收藏 引用 所属分类: 设计模式

定义:
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。

下面来看一个例子:


Room(房间):是装饰模式中的一个抽象类
Hall(大厅):是一个被装饰对象
Cookroom(厨房):同上

Decorator:装饰物的抽象类
Fan(风扇):一个装饰物
Window(窗口):同上

  大厅和厨房都可以用风扇或窗口来装饰。下面来看GetDescription方法和 PrintDescription方法的实现:
string Room::PrintDescription()
{
   cout<< GetDescription()<<endl;
}

string Fan::GetDescription()
{
    return m_room.GetDescription() + "It has fan.";
}

string Window::GetDescription()
{
    return m_room.GetDescription() + " It has window.";
}

string Hall::GetDescription()
{
   return "This is hall.";
}

string Cookroom::GetDescription()
{
   return "This is cookroom";
}

string Cookroom::GetDescription()
{
    return "This is cookroom";
}
 
  另外还要注意装饰物的构造方法:
Decorator::Decorator(Room *pRoom) : Room()
{
}

 Fan::Fan( Room * pRoom) : Decorator(pRoom)
{
}

Cookroom::Cookroom(Room * pRoom) : Decorator(pRoom)
{
}

使用方法:

Hall * pHall;
pHall = new Cookroom( new Fan( new Hall() ) );
pHall->PrintDescription();

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理