Design Patterns provide solutions to the commonly occurring problems
in software design. The design patterns were first introduced by GoF(Gang of Four)
where they described the common patterns as problems which occur over and over again and solutions to those problems.
Design patterns have four essential elements:
The pattern name
is a handle we can use to describe a design problem, its solutions, and consequences in a word or two.The problem
describes when to apply the pattern.The solution
describes the elements that make up the design, their relationships, responsibilities, and collaborations.The consequences
are the results and trade-offs of applying the pattern.Advantages of design patterns:
Design patterns can be classified into three categories:
Creational Pattern
- They are concerned with how the object can be created and they isolate the details of object creation.
Structural Pattern
- They design the structure of classes and objects so that they can compose to achieve larger results.
Behavioral Pattern
- They are concerned with interaction among objects and responsibility of objects.
Singleton Pattern:
It is a type of creational pattern
which provides a mechanism to have only one and one object of a given type and provides a global point of access.
e.g. Singleton can be used in database operations, where we want database object to maintain data consistency.
Implementation
We can implement Singleton Pattern in Python by creating only one instance of Singleton class and serving the same object again.
class Singleton(object):
def __new__(cls):
# hasattr method checks if the class object an instance property or not.
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
s = Singleton()
print ("Object created", s)
s1 = Singleton()
print ("Object2 created", s1)
Output:
('Object created', <__main__.Singleton object at 0x10a7cc310>)
('Object2 created', <__main__.Singleton object at 0x10a7cc310>)
Note that in languages like C++ or Java, this pattern is implemented by making the constructor private and creating a static method that does the object initialization. This way, one object gets created on the first call and class returns the same object thereafter. But in Python, we do not have any way to create private constructors.
Factory Pattern
Factory pattern is also a Creational pattern
. The term factory
means that a class is responsible for creating objects of other types. There is a class that acts as a factory which has objects and methods associated with it. The client creates an object by calling the methods with certain parameters and factory creates the object of the desired type and return it to the client.
from abc import ABCMeta, abstractmethod
class Music():
__metaclass__ = ABCMeta
@abstractmethod
def do_play(self):
pass
class Mp3(Music):
def do_play(self):
print ("Playing .mp3 music!")
class Ogg(Music):
def do_play(self):
print ("Playing .ogg music!")
class MusicFactory(object):
def play_sound(self, object_type):
return eval(object_type)().do_play()
if __name__ == "__main__":
mf = MusicFactory()
music = input("Which music you want to play Mp3 or Ogg")
mf.play_sound(music)
Output:
Which music you want to play Mp3 or Ogg"Ogg"
Playing .ogg music!
MusicFactory
is the factory class here that creates either an object of type Mp3
or Ogg
depending on the choice user provides.