Posted on 2008-11-08 13:26
Herbert 閱讀(743)
評論(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();