練習 裝飾模式

2021-09-27 03:24:23 字數 1483 閱讀 1225

裝飾模式:將裝飾功能單獨放在乙個類的方法中,並在該方法中呼叫父類的同名方法,從而達到增添功能的目的。

以下用兩種方式實現裝飾模式,但是都出現了中間環節被「跳過」的情況: +after correcting

#include using namespace std;

class phonecall

;class addphonecall :public phonecall

;class musicphonecall :public phonecall

;int main()

phonecall::phonecall()

void phonecall::call()

addphonecall::addphonecall(phonecall& pc) :_pc(pc)

void addphonecall::call()

musicphonecall::musicphonecall(phonecall& pc) :_pc(pc)

void musicphonecall::call()

輸出:

phonecall constructor

phonecall constructor

musicphonecall constructor

phonecall constructor

addphonecall constructor

addvertising...

calling...

#includeusing namespace std;

class component

};class decorator: public component

virtual void operation() };

class concretedecoratora: public decorator

};class concretedecoratorb : public decorator

};int main()

輸出:

component

concretedecoratorb

解答:這兩種實現方式的問題是一樣的。結合建構函式的呼叫情況,我想會不會是因為引數型別的問題導致concretedecoratora的建構函式沒有被呼叫,所以中間環節被「跳過」了。後來在csdn問答裡提問,得到的回答和我的猜測差不多,但更詳細,以下為該使用者的回答(感謝!):

b.setcomponent(a);的時候的方法是類decorator裡的

引數是component,而a的型別是concretedecoratora,被退化為decorator,再退化為component

所以自始至終都沒有使用過concretedecoratora:類裡的任何東西,自然不會輸出concretedecoratora

——豆丷

裝飾器和單例模式練習

coding utf 8 usr bin env python3 coding utf 8 time 2020 5 15 23 46 author 小多肉 email 1021181701 qq.com todo 1 實現乙個網路請求超時重試的裝飾器,裝飾下面的功能函式 如果請求網路超時,或者連線超...

裝飾器的練習

1.比如之前所寫的管理員登陸系統,可以加上與使用者之間的判定,這時候就可以用裝飾器來完成 root admin redhat 在實際的應用場景中,會採用多個裝飾器先驗證是否登陸成功,再驗證許可權是否足夠 import functools import inspect def is admin fun...

python 裝飾器練習

import time import functools def add log fun functools.wraps fun start time time.time res fun args,kwargs end time time.time fun.name end time start t...