Factory method is a creational design pattern used to create concrete implementations of a common interface. It separates the process of creating an object from the code that depends on the interface of the object. It has the best ways of creating objects. Objects are created without exposing the logic to the client and the clients uses the same common interface to create a new type of the object.
Factory design patterns are implemented in python using the factory methods. It is used mainly to enhance loose coupling in code through the creation of an abstract class that will be used to create different types of objects that share some common attributes and functionality.
The python implementation of the factory method:
class Button(object): html = "" def get_html(self): return self.html class Image(Button): html = "<img></img>" () if __name__ == '__main__': button_obj = ButtonFactory() button = ['image','input','flash'] for b in button: print(button_obj.create_button(b).get_html())
The Class button() helps you create the HTML tags and the associated HTML page. The logic of the code will not be accessed by the client.
ProBook:~/Desktop/InfosecAddicts/python design pattern$ python factory.py <img></img> <input></input> <obj></obj>
The result of the code includes the logic of the HTML tags with a specified value.
Pros and Cons
- New features can be added without necessarily affecting the existing client code.
- It helps uphold the single responsibility principle where classes and objects that handle specific functionality resulting in better code.
- Less readability – When more classes are created they eventually lead to less readability.