-
Creational Patterns
A creational pattern provides a particular instantiation mechanism. It can be aparticular object factory or even a class factory.
This is an important pattern in compiled languages such as C, since it is harder togenerate types on-demand at run time.
Useful Design Patterns
But this feature is built-in in Python, for instance the type built-in, which lets youdefine a new type by code:
>>> MyType = type('MyType', (object,), {'a': 1})
>>> ob = MyType()
>>> type(ob)
<class '__main__.MyType'>
>>> ob.a
1
>>> isinstance(ob, object)
True
Classes and types are built-in factories and you can interact with class and objectgeneration using meta-classes, for instance (see Chapter 3). These features are thebasics to implement the Factory design pattern and we won't further describe it inthis section.
Besides Factory, the only other creational design pattern from the GoF that isinteresting to describe in Python is Singleton.
Singleton
Singleton restricts instantiation of a class to one object.
The Singleton pattern makes sure that a given class has always only one livinginstance in the application. This can be used, for example, when you want to restricta resource access to one and only one memory context in the process. For instance,a database connector class can be a Singleton that deals with synchronization andmanages its data in memory. It makes the assumption that no other instance isinteracting with the database in the meantime.
This pattern can simplify a lot the way concurrency is handled in an application.Utilities that provide application-wide functions are often declared as Singletons.For instance, in web applications, a class that is in charge of reserving a uniquedocument ID would benefit from the Singleton pattern. There should be one andonly one utility doing this job.
Implementing the Singleton pattern is straightforward with the __new__ method:>>> class Singleton(object):
.........
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
[ 326 ]
... cls._instance = orig.__new__(cls, *args, **kw)
... return cls._instance
...
>>> class MyClass(Singleton):
... a =1
...
>>> one = MyClass()>>> two = MyClass()>>> two.a = 3
>>> one.a
3
Although the problem with this pattern is subclassing; all instances will be instancesof MyClass no matter what the method resolution order (__mro__) says:
>>> class MyOtherClass(MyClass):... b= 2
...
>>> three = MyOtherClass()
>>> three.b
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'MyClass' object has no attribute 'b'
To avoid this limitation, Alex Martelli proposed an alternative implementation basedon shared state called Borg.
The idea is quite simple. What really matters in the Singleton pattern is not thenumber of living instances a class has, but rather the fact that they all share the samestate at all times. So Alex Martelli came up with a class that makes all instances of theclass share the same __dict__:
>>> class Borg(object):
-
... _state = {}
-
... def __new__(cls, *args, **kw):
-
... ob = super(Borg, cls).__new__(cls, *args, **kw)
-
... ob.__dict__ = cls._state
-
... return ob
...
>>> class MyClass(Borg):
... a =1
...
>>> one = MyClass()>>> two = MyClass()>>> two.a = 3
>>> one.a
[ 327 ]
Chapter 14
Useful Design Patterns
3
>>> class MyOtherClass(MyClass):... b= 2
...
>>> three = MyOtherClass()
>>> three.b
2
>>> three.a
3
>>> three.a = 2
>>> one.a
2
This fixes the subclassing issue, but is still dependent on how the subclass codeworks. For instance, if __getattr__ is overridden, the pattern can be broken.
Nevertheless, Singletons should not have several levels of inheritance. A class that ismarked as a Singleton is already specific.
That said, this pattern is considered by many developers as a heavy way to deal withuniqueness in an application. If a Singleton is needed, why not use a module withfunctions instead, since a Python module is a Singleton?
The Singleton factory is an implicit way of dealing with the uniquenessin your application. You can live without it. Unless you are working in aframework à la Java that requires such a pattern, use a module insteadof a class.
-
Creational Patterns
A creational pattern provides a particular instantiation mechanism. It can be aparticular object factory or even a class factory.
This is an important pattern in compiled languages such as C, since it is harder togenerate types on-demand at run time.
Useful Design Patterns
But this feature is built-in in Python, for instance the type built-in, which lets youdefine a new type by code:
>>> MyType = type('MyType', (object,), {'a': 1})
>>> ob = MyType()
>>> type(ob)
<class '__main__.MyType'>
>>> ob.a
1
>>> isinstance(ob, object)
True
Classes and types are built-in factories and you can interact with class and objectgeneration using meta-classes, for instance (see Chapter 3). These features are thebasics to implement the Factory design pattern and we won't further describe it inthis section.
Besides Factory, the only other creational design pattern from the GoF that isinteresting to describe in Python is Singleton.
Singleton
Singleton restricts instantiation of a class to one object.
The Singleton pattern makes sure that a given class has always only one livinginstance in the application. This can be used, for example, when you want to restricta resource access to one and only one memory context in the process. For instance,a database connector class can be a Singleton that deals with synchronization andmanages its data in memory. It makes the assumption that no other instance isinteracting with the database in the meantime.
This pattern can simplify a lot the way concurrency is handled in an application.Utilities that provide application-wide functions are often declared as Singletons.For instance, in web applications, a class that is in charge of reserving a uniquedocument ID would benefit from the Singleton pattern. There should be one andonly one utility doing this job.
Implementing the Singleton pattern is straightforward with the __new__ method:>>> class Singleton(object):
.........
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
[ 326 ]
... cls._instance = orig.__new__(cls, *args, **kw)
... return cls._instance
...
>>> class MyClass(Singleton):
... a =1
...
>>> one = MyClass()>>> two = MyClass()>>> two.a = 3
>>> one.a
3
Although the problem with this pattern is subclassing; all instances will be instancesof MyClass no matter what the method resolution order (__mro__) says:
>>> class MyOtherClass(MyClass):... b= 2
...
>>> three = MyOtherClass()
>>> three.b
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'MyClass' object has no attribute 'b'
To avoid this limitation, Alex Martelli proposed an alternative implementation basedon shared state called Borg.
The idea is quite simple. What really matters in the Singleton pattern is not thenumber of living instances a class has, but rather the fact that they all share the samestate at all times. So Alex Martelli came up with a class that makes all instances of theclass share the same __dict__:
>>> class Borg(object):
-
... _state = {}
-
... def __new__(cls, *args, **kw):
-
... ob = super(Borg, cls).__new__(cls, *args, **kw)
-
... ob.__dict__ = cls._state
-
... return ob ... >>> class MyClass(Borg):
... a =1
...
>>> one = MyClass()>>> two = MyClass()>>> two.a = 3
>>> one.a
[ 327 ]
Chapter 14
Useful Design Patterns
3
>>> class MyOtherClass(MyClass):... b= 2
...
>>> three = MyOtherClass()
>>> three.b
2
>>> three.a
3
>>> three.a = 2
>>> one.a
2
This fixes the subclassing issue, but is still dependent on how the subclass codeworks. For instance, if __getattr__ is overridden, the pattern can be broken.
Nevertheless, Singletons should not have several levels of inheritance. A class that ismarked as a Singleton is already specific.
That said, this pattern is considered by many developers as a heavy way to deal withuniqueness in an application. If a Singleton is needed, why not use a module withfunctions instead, since a Python module is a Singleton?
The Singleton factory is an implicit way of dealing with the uniquenessin your application. You can live without it. Unless you are working in aframework à la Java that requires such a pattern, use a module insteadof a class.
instantiation
- n.实例化;用具体例子说明;例示
-
instantiation是什么意思,词典释义与在线翻译:
行业释义
英英释义
- a representation of an idea in the form of an instance of it;
"how many instantiations were found?"
instantiation的用法和样例:
例句
- An object is instantiation of a class.
对象是类的实列。 - Needed for instantiation and views.
听 听 听 听 听-- raw symbol map. - A new rule is created through the instantiation of a template.
透过范本实例定义新的规则。 - Use delegate inference instead of explicit delegate instantiation.
使用委托定义而不是直接的委托实例。 - The target instance to be created on template instantiation.
将被创建在模板例示上的目标范例。