我在元類中找到了很多鏈接,其中大多數提到它們對於實現工廠方法很有用。你能給我看一個使用元類來實現設計模式的例子嗎?在Python中使用元類實現工廠設計模式
6
A
回答
2
我很想聽聽人們對這個意見,但我認爲這是你想要做
class FactoryMetaclassObject(type):
def __init__(cls, name, bases, attrs):
"""__init__ will happen when the metaclass is constructed:
the class object itself (not the instance of the class)"""
pass
def __call__(*args, **kw):
"""
__call__ will happen when an instance of the class (NOT metaclass)
is instantiated. For example, We can add instance methods here and they will
be added to the instance of our class and NOT as a class method
(aka: a method applied to our instance of object).
Or, if this metaclass is used as a factory, we can return a whole different
classes' instance
"""
return "hello world!"
class FactorWorker(object):
__metaclass__ = FactoryMetaclassObject
f = FactorWorker()
print f.__class__
內容示例
你會看到的結果是:type'str'
0
沒有必要。你可以override a class's __new__()
method爲了返回一個完全不同的對象類型。
+0
我不認爲你可以用元類...(也許你可以 - 如果讓我知道,我會學到一些東西:)) – RyanWilcox 2010-03-14 20:52:44
2
你可以找到wikibooks/python,here和here一些有用的例子
+1
這些都是確切的我偶然發現的鏈接。我找不到一個工廠的具體例子(雖然他們都提到了它)... – olamundo 2010-03-14 21:01:37
相關問題
- 1. 如何在Ocaml中實現工廠設計模式
- 2. 在單元測試中使用工廠/抽象工廠設計模式
- 3. 工廠模式設計
- 4. 工廠設計模式:工廠可以保存實例嗎?
- 5. 實現工廠設計模式與春天annotaion
- 6. Java通用工廠模式實現
- 7. 使用Symfony2實現工廠模式的最佳實踐
- 8. 無反射的工廠模式實現
- 9. 如何實現工廠模式?
- 10. 如何在使用貓鼬時實現工廠模式?
- 11. PHP設計模式工廠,倉庫和...?
- 12. 工廠設計模式問題
- 13. 工廠設計模式(需要批判)
- 14. 工廠方法設計模式
- 15. 工廠設計模式擴展
- 16. 工廠設計模式VS構造器
- 17. 設計模式名稱:是工廠嗎?
- 18. 抽象工廠設計模式 - C#
- 19. 工廠設計模式禁止?
- 20. 設計模式 - 抽象工廠 - BombedMazeFactory
- 21. 抽象工廠設計模式c#
- 22. 頁面工廠設計模式硒
- 23. 工廠模式,實現工廠動態列表
- 24. 使用實體類設計模式
- 25. 工廠和非工廠設計模式差異
- 26. iOS設計模式實現
- 27. 驗證工廠類設計
- 28. 替代工廠(類設計)
- 29. 使用彈簧實現工廠方法模式
- 30. 使用ReSharper創建實現特定設計模式的類
您能否在示例中添加一點「重要性」,即將一些自定義應用於創建的對象? – olamundo 2010-03-14 21:03:02