This article example describes the principle and usage of Python design patterns of the hedonic pattern. Shared for your reference, as follows:
Flyweight Pattern: Uses sharing techniques to efficiently support a large number of fine-grained objects.
Here is a demo of the hedonic pattern:
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'Andy' """ big talk about design patterns design pattern——hedonic model hedonic model(Flyweight Pattern):Efficiently support large numbers of fine-grained objects using shared technologies Instances of a class,Created only on first use,Other times the same instance is used,Reduced memory overhead """ # Abstract website class class Website(object): def use(self): pass # Site-specific categories class ConcreteWebsite(Website): def __init__(self, name): = name def use(self): print "Web site categorization", # Unshared site category class UnshareConcreteWebsite(Website): def __init__(self, name): = name def use(self): print "Do not share website categorization", # Website Factory class WebsiteFactory(object): def __init__(self): = dict() # Get the website class If it exists, return it directly, if it does not exist, return it after you build it. def get_website(self, key): if not key in : [key] = ConcreteWebsite(key) return [key] # of website instances def get_website_count(self): return len(()) if __name__ == "__main__": factory = WebsiteFactory() f1 = factory.get_website("blog") f2 = factory.get_website("blog") f3 = factory.get_website("blog") f4 = factory.get_website("website") f5 = factory.get_website("website") f6 = factory.get_website("website") f7 = UnshareConcreteWebsite("test") () () () () () () ()
Run results:
The design of the above class is shown below:
The hedonic pattern can avoid the overhead of a large number of very similar classes, in program design, sometimes generate a large number of fine-grained class instances to represent the data, if these instances are basically the same except for a few parameters, it is possible to have the parameters outside the instances, and in the method call, they are passed in, you can dramatically reduce the number of individual instances through the shared
More about Python related content can be viewed on this site's topic: thePython Data Structures and Algorithms Tutorial》、《Python Socket Programming Tips Summary》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope that what I have said in this article will help you in Python programming.