設計模式c++學習筆記之十三(decorator裝飾模式)
裝飾模式,動態地給乙個物件新增一些額外的職責。就增加功能來說,decorator模式相比生成子類更為靈活。
13.1.解釋
main(),老爸
ischoolreport,成績單介面
cfourthgradeschoolreport,四年級成績單
reportdecorator,成績單裝飾器基類
highscoredecorator,最高分裝飾器
sortdecorator,班級排名裝飾器
說明:對「四年級成績單」進行裝飾,reportdecorator必然有乙個private變數指向ischoolreport。
注意:看**:
// decorator.cpp//主程式
#include "stdafx.h"
#include "ischoolreport.h"
#include "fouthgradeschoolreport.h"
#include "sugarfouthgradeschoolreport.h"
#include "highscoredecorator.h"
#include "sortdecorator.h"
#include
using std::cout;
using std::endl;
void doit()
void donew()
int _tmain(int argc, _tchar* argv)
#pragma once
#include
using std::string;
class ischoolreport
virtual ~ischoolreport(void)
virtual void report() = 0;
virtual void sign(string name) = 0;
};#pragma once
#include "ischoolreport.h"
class cfouthgradeschoolreport :
public ischoolreport
;#include "stdafx.h"
#include "fouthgradeschoolreport.h"
#include
using std::cout;
using std::endl;
using std::string;
cfouthgradeschoolreport::cfouthgradeschoolreport(void)
cfouthgradeschoolreport::~cfouthgradeschoolreport(void)
void cfouthgradeschoolreport::report()
void cfouthgradeschoolreport::sign(string name)
#pragma once
#include "ischoolreport.h"
class creportdecorator :
public ischoolreport
;#include "stdafx.h"
#include "reportdecorator.h"
#include
using std::string;
creportdecorator::creportdecorator(ischoolreport *psr)
creportdecorator::~creportdecorator(void)
void creportdecorator::report()
void creportdecorator::sign( string name )
#pragma once
#include "reportdecorator.h"
#include "ischoolreport.h"
class chighscoredecorator :
public creportdecorator
;#include "stdafx.h"
#include "highscoredecorator.h"
#include
using std::cout;
using std::endl;
chighscoredecorator::chighscoredecorator( ischoolreport *psr ) : creportdecorator(psr)
chighscoredecorator::~chighscoredecorator(void)
void chighscoredecorator::report()
void chighscoredecorator::reporthighscore()
#pragma once
#include "reportdecorator.h"
#include "ischoolreport.h"
class csortdecorator :
public creportdecorator
;#include "stdafx.h"
#include "sortdecorator.h"
#include
using std::cout;
using std::endl;
csortdecorator::csortdecorator( ischoolreport *psr ) : creportdecorator(psr)
csortdecorator::~csortdecorator(void)
void csortdecorator::reportsort()
void csortdecorator::report()
C 設計模式之裝飾模式 Decorator
裝飾模式是一種經典的類功能擴充套件模式,其精髓在裝飾類使用繼承加聚合的方式獲得介面和要實現物件,然後通過自己實現擴充套件介面 作用裝飾模式通過裝飾類動態地將責任附加到物件上,若要擴充套件功能,無需通過繼承增加子類就能擴充套件物件的新功能,提供了比繼承更有彈性的替代方案,避免了子類數量膨脹帶來的系統臃...
Java設計模式之Decorator模式
感覺比之前理解深了一點,紅字為新理解的內容,小白看過來 首先,不抽象,舉個例子。我要去喝咖啡,咖啡店裡有兩種咖啡,一種摩卡的,一種藍山的,摩卡的50塊,藍山的100塊。買了咖啡後還能放配料,有牛奶和伴侶。牛奶10塊一包,伴侶高階一 點,15塊一包。現在店裡新上貨一種配料方糖,5塊錢一包,現在把上述的...
設計模式之裝飾模式(Decorator)
現在有這樣乙個場景,需要給乙個人穿不同風格的衣服,那在物件導向的思想下應該怎麼寫呢 class person public void show abstract class finery class tshirts extends finery class pants extends finery ...