使用 metaclass 实现工厂设计模式

10 投票
3 回答
7568 浏览
提问于 2025-04-15 20:25

我发现很多关于元类的链接,大部分都提到它们在实现工厂方法时很有用。你能给我举个例子,说明如何用元类来实现设计模式吗?

3 个回答

1

其实没必要这么做。你可以重写一个类的 __new__() 方法,这样就能返回一个完全不同类型的对象。

2

你可以在以下链接找到一些有用的例子:wikibooks/python这里这里

3

我很想听听大家对此的看法,不过我觉得这就是你想要做的一个例子。

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__

你会看到的结果是:类型为 'str'

撰写回答