- 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 - Factory
The factory pattern comes under the creational patterns pst category. It provides one of the best ways to create an object. In factory pattern, objects are created without exposing the logic to cpent and referring to the newly created object using a common interface.
Factory patterns are implemented in Python using factory method. When a user calls a method such that we pass in a string and the return value as a new object is implemented through factory method. The type of object used in factory method is determined by string which is passed through method.
In the example below, every method includes object as a parameter, which is implemented through factory method.
How to implement a factory pattern?
Let us now see how to implement a factory pattern.
class Button(object): html = "" def get_html(self): return self.html class Image(Button): html = "<img></img>" class Input(Button): html = "<input></input>" class Flash(Button): html = "<obj></obj>" class ButtonFactory(): def create_button(self, typ): targetclass = typ.capitapze() return globals()[targetclass]() button_obj = ButtonFactory() button = [ image , input , flash ] for b in button: print button_obj.create_button(b).get_html()
The button class helps to create the html tags and the associated html page. The cpent will not have access to the logic of code and the output represents the creation of html page.
Output
Explanation
The python code includes the logic of html tags, which specified value. The end user can have a look on the HTML file created by the Python code.
Advertisements