程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python design mode - structural mode - Decorative mode

編輯:Python

Catalog

List of articles

  • Catalog
  • Decoration mode
  • Application scenarios
  • Code example

Decoration mode

Decoration mode , It means that you don't need to change the original class and use inheritance , Dynamically extend the function of an object . It does this by creating a wrapper object , That is to say Python To wrap the actual object .

stay Python Methods of dynamically extending object functions in , The simplest way is by copying __getattr__ function , stay getattr() Write the functions we need to expand ; Or implement a decorator .

Characteristics of decoration mode :

  1. Decorative objects have the same interface as real objects . In this way, the client object can interact with the decoration object in the same way as the real object .
  2. The decoration object contains a reference to a real object (reference).
  3. The decoration object accepts all requests from the client . It forwards these requests to real objects .
  4. Decoration objects can add some additional functions before or after forwarding these requests . This ensures that at run time , You can add additional functions outside without modifying the structure of a given object . In object-oriented design , It is usually achieved by inheritance

Application scenarios

Code example


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved