Python Design Patterns
Master Clean Coding with Design Patterns - By DarchumsTech
📘 What Are Design Patterns?
Design Patterns are reusable solutions to common problems in software design. They offer proven ways to solve problems by structuring your code more efficiently.
🎯 Benefits of Using Design Patterns
- Write cleaner and maintainable code
- Enhance software scalability
- Improve team collaboration and code consistency
🔒 1. Singleton Pattern
Ensures only one instance of a class is created.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2) # True
🏭 2. Factory Pattern
Creates objects without exposing the creation logic.
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Bark"
class Cat(Animal):
def speak(self):
return "Meow"
class AnimalFactory:
def create_animal(self, animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
factory = AnimalFactory()
animal = factory.create_animal("dog")
print(animal.speak()) # Bark
📦 3. Strategy Pattern
Allows you to change the behavior of a class at runtime.
class Strategy:
def execute(self, a, b):
pass
class Add(Strategy):
def execute(self, a, b):
return a + b
class Multiply(Strategy):
def execute(self, a, b):
return a * b
class Context:
def __init__(self, strategy):
self.strategy = strategy
def execute_strategy(self, a, b):
return self.strategy.execute(a, b)
context = Context(Add())
print(context.execute_strategy(3, 4)) # 7
context = Context(Multiply())
print(context.execute_strategy(3, 4)) # 12
🔔 4. Observer Pattern
Lets one object notify other objects about state changes.
class Subject:
def __init__(self):
self._observers = []
def register(self, observer):
self._observers.append(observer)
def notify_all(self, msg):
for observer in self._observers:
observer.notify(msg)
class Observer:
def notify(self, msg):
print("Received:", msg)
subject = Subject()
observer1 = Observer()
observer2 = Observer()
subject.register(observer1)
subject.register(observer2)
subject.notify_all("New update available!")
🔁 5. Decorator Pattern
Attach new behavior to objects without modifying them.
def make_bold(func):
def wrapper():
return "<b>" + func() + "</b>"
return wrapper
@make_bold
def greet():
return "Hello"
print(greet()) # <b>Hello</b>
✅ Conclusion
Understanding and applying design patterns can take your Python development to the next level. Start simple, practice often, and adopt these principles to write smarter code.
Comments
Post a Comment