Flyweight pattern: Use shared technology to effectively support a large number of fine-grained objects.
Here is a demo of the enjoy meta mode:
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 4 __author__='Andy'5 """6 Liar design Mode7 design mode--Enjoy meta mode8 enjoy meta mode (Flyweight pattern): Use sharing technology to effectively support large numbers of fine-grained objects9 An instance of a class is created only on the first use, and at other times with the same instance, reducing the overhead of memoryTen """ One #Abstract Web site class A classWebsite (object): - - defUse (self): the Pass - - #specific website class - classConcretewebsite (Website): + - def __init__(self, name): +Self.name =name A at defUse (self): - Print "Site Categories", Self.name - #Web site classes that are not shared - classUnshareconcretewebsite (Website): - def __init__(self, name): -Self.name =name in - defUse (self): to Print "do not share site categories", Self.name + - #website Factory the classWebsitefactory (object): * $ def __init__(self):Panax NotoginsengSelf.hashtable =dict () - the #Gets the site class if there is a direct return if it does not exist and returns after it has been built. + defget_website (self, key): A if notKeyinchself.hashtable: theSelf.hashtable[key] =concretewebsite (Key) + returnSelf.hashtable[key] - $ #Number of site instances $ defGet_website_count (self): - returnLen (Self.hashtable.keys ()) - the if __name__=="__main__": -Factory =websitefactory ()WuyiF1 = Factory.get_website ("Blog") theF2 = Factory.get_website ("Blog") -F3 = Factory.get_website ("Blog") WuF4 = Factory.get_website ("website") -F5 = Factory.get_website ("website") AboutF6 = Factory.get_website ("website") $F7 = Unshareconcretewebsite ("Test") - F1.use () - F2.use () - F3.use () A F4.use () + F5.use () the F6.use () -F7.use ()
The design of the above class is as follows:
Enjoy meta-mode can avoid a lot of very similar classes of overhead, in programming, sometimes generate a large number of fine-grained class instances to represent the data, if these instances in addition to a few parameters are basically the same, you can put the parameters out of the instance, in the method call, pass them in, you can greatly reduce the number of individual instances by sharing
Andy
Source: http://www.cnblogs.com/onepiece-andy/
The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the author's consent must be in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.
Big talk design pattern python implementation-Enjoy meta mode