Design pattern in object-oriented software development.
Design patterns are reusable solutions to common problems that occur in software design. They represent best practices and can speed up the development process by providing tested, proven development paradigms. In this unit, we will explore some of the most commonly used design patterns in Python.
The Singleton pattern restricts the instantiation of a class to a single instance. It is used in logging, driver objects, caching, thread pools, and database connections.
class Singleton: __instance = None @staticmethod def getInstance(): if Singleton.__instance == None: Singleton() return Singleton.__instance def __init__(self): if Singleton.__instance != None: raise Exception("This class is a singleton!") else: Singleton.__instance = self
The Factory pattern provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
class Dog: def __init__(self, name): self._name = name def speak(self): return "Woof!" class Cat: def __init__(self, name): self._name = name def speak(self): return "Meow!" def get_pet(pet="dog"): pets = dict(dog=Dog("Hope"), cat=Cat("Peace")) return pets[pet] d = get_pet("dog") print(d.speak()) c = get_pet("cat") print(c.speak())
The Prototype pattern is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.
import copy class Prototype: def __init__(self): self._objects = {} def register_object(self, name, obj): self._objects[name] = obj def unregister_object(self, name): del self._objects[name] def clone(self, name, **attr): obj = copy.deepcopy(self._objects.get(name)) obj.__dict__.update(attr) return obj
The Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.
class Director: __builder = None def setBuilder(self, builder): self.__builder = builder def getCar(self): car = Car() # First goes the body body = self.__builder.getBody() car.setBody(body) # Then engine engine = self.__builder.getEngine() car.setEngine(engine) # And four wheels i = 0 while i < 4: wheel = self.__builder.getWheel() car.attachWheel(wheel) i += 1 return car
By understanding and implementing these design patterns, you can significantly improve the efficiency of your Python programming and the quality of your code.