Python Design Patterns Tutorial
Python Design Patterns Resources
Selected Reading
- Exception Handling
- Python Design Patterns - Anti
- Concurrency in Python
- Strings & Serialization
- Python Design Patterns - Queues
- Python Design Patterns - Sets
- Lists Data Structure
- Dictionaries
- Python Design Patterns - Iterator
- Object Oriented Concepts Implementation
- Object Oriented
- Abstract Factory
- Python Design Patterns - Flyweight
- Python Design Patterns - Template
- Python Design Patterns - Strategy
- Python Design Patterns - State
- Python Design Patterns - Observer
- Chain of Responsibility Pattern
- Python Design Patterns - Proxy
- Python Design Patterns - Decorator
- Python Design Patterns - Adapter
- Python Design Patterns - Command
- Python Design Patterns - Facade
- Python Design Patterns - Prototype
- Python Design Patterns - Builder
- Python Design Patterns - Factory
- Python Design Patterns - Singleton
- Model View Controller Pattern
- Python Design Patterns - Gist
- Introduction
- Python Design Patterns - Home
Python Design Patterns Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Python Design Patterns - Flyweight
Python Design Patterns - Flyweight
The flyweight patterb comes under the structural design patterns category. It provides a way to decrease object count. It includes various features that help in improving apppcation structure. The most important feature of the flyweight objects is immutable. This means that they cannot be modified once constructed. The pattern uses a HashMap to store reference objects.
How to implement the flyweight pattern?
The following program helps in implementing the flyweight pattern −
class ComplexGenetics(object): def __init__(self): pass def genes(self, gene_code): return "ComplexPatter[%s]TooHugeinSize" % (gene_code) class Famipes(object): family = {} def __new__(cls, name, family_id): try: id = cls.family[family_id] except KeyError: id = object.__new__(cls) cls.family[family_id] = id return id def set_genetic_info(self, genetic_info): cg = ComplexGenetics() self.genetic_info = cg.genes(genetic_info) def get_genetic_info(self): return (self.genetic_info) def test(): data = (( a , 1, ATAG ), ( a , 2, AAGT ), ( b , 1, ATAG )) family_objects = [] for i in data: obj = Famipes(i[0], i[1]) obj.set_genetic_info(i[2]) family_objects.append(obj) for i in family_objects: print "id = " + str(id(i)) print i.get_genetic_info() print "similar id s says that they are same objects " if __name__ == __main__ : test()
Output
The above program generates the following output −
Advertisements