Structural design patterns in software engineering are concerned with the composition of classes and objects to form larger structures. These patterns simplify the relationships between different components, ensuring flexibility and reusability of code. In Python, structural design patterns help developers organize code, manage object relationships, and simplify the implementation of complex systems.
This document covers the most commonly used structural design patterns in Python:
The Adapter pattern allows objects with incompatible interfaces to work together. It wraps an existing class with a new interface, making it compatible with the client code.
class EuropeanSocket:
def voltage(self):
return 230
class AmericanAppliance:
def connect(self, voltage):
if voltage == 110:
print("Appliance running")
else:
print("Voltage mismatch!")
class Adapter:
def __init__(self, socket):
self.socket = socket
def get_voltage(self):
return 110 # Convert to 110V
socket = EuropeanSocket()
adapter = Adapter(socket)
appliance = AmericanAppliance()
appliance.connect(adapter.get_voltage())
The Bridge pattern separates abstraction from its implementation, allowing both to vary independently. This is useful in scenarios where multiple abstractions can share the same implementation logic.
class DrawingAPI:
def draw_circle(self, x, y, radius):
pass
class DrawingAPI1(DrawingAPI):
def draw_circle(self, x, y, radius):
print(f"API1.circle at {x},{y} with radius {radius}")
class DrawingAPI2(DrawingAPI):
def draw_circle(self, x, y, radius):
print(f"API2.circle at {x},{y} with radius {radius}")
class Circle:
def __init__(self, x, y, radius, api):
self.x = x
self.y = y
self.radius = radius
self.api = api
def draw(self):
self.api.draw_circle(self.x, self.y, self.radius)
circle1 = Circle(1, 2, 3, DrawingAPI1())
circle2 = Circle(4, 5, 6, DrawingAPI2())
circle1.draw()
circle2.draw()
The Composite pattern allows you to compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions uniformly.
class Component:
def show(self):
pass
class Leaf(Component):
def __init__(self, name):
self.name = name
def show(self):
print(self.name)
class Composite(Component):
def __init__(self, name):
self.name = name
self.children = []
def add(self, component):
self.children.append(component)
def show(self):
print(f"{self.name}")
for child in self.children:
child.show()
leaf1 = Leaf("Leaf 1")
leaf2 = Leaf("Leaf 2")
composite = Composite("Composite 1")
composite.add(leaf1)
composite.add(leaf2)
root = Composite("Root")
root.add(composite)
root.show()
The Decorator pattern allows behavior to be added to individual objects dynamically, without affecting the behavior of other objects from the same class.
class Coffee:
def cost(self):
return 5
class MilkDecorator:
def __init__(self, coffee):
self.coffee = coffee
def cost(self):
return self.coffee.cost() + 2
class SugarDecorator:
def __init__(self, coffee):
self.coffee = coffee
def cost(self):
return self.coffee.cost() + 1
basic = Coffee()
milk = MilkDecorator(basic)
sugar = SugarDecorator(milk)
print("Total cost:", sugar.cost())
The Facade pattern provides a unified interface to a set of interfaces in a subsystem, making the subsystem easier to use.
class CPU:
def freeze(self):
print("Freezing CPU")
def execute(self):
print("Executing instructions")
class Memory:
def load(self, position, data):
print(f"Loading {data} to {position}")
class HardDrive:
def read(self, lba, size):
return "bootloader"
class ComputerFacade:
def __init__(self):
self.cpu = CPU()
self.memory = Memory()
self.hd = HardDrive()
def start(self):
self.cpu.freeze()
data = self.hd.read(0, 100)
self.memory.load(0, data)
self.cpu.execute()
computer = ComputerFacade()
computer.start()
The Flyweight pattern reduces memory usage by sharing common parts of object state between multiple objects instead of storing all data in each object.
class Flyweight:
def __init__(self, shared_state):
self.shared_state = shared_state
def operation(self, unique_state):
print(f"Shared: {self.shared_state}, Unique: {unique_state}")
class FlyweightFactory:
def __init__(self):
self._flyweights = {}
def get_flyweight(self, shared_state):
key = tuple(shared_state)
if key not in self._flyweights:
self._flyweights[key] = Flyweight(shared_state)
return self._flyweights[key]
factory = FlyweightFactory()
fw1 = factory.get_flyweight(["A", "B"])
fw2 = factory.get_flyweight(["A", "B"])
fw3 = factory.get_flyweight(["X", "Y"])
fw1.operation("1")
fw2.operation("2")
fw3.operation("3")
The Proxy pattern provides a surrogate or placeholder for another object to control access to it.
class RealSubject:
def request(self):
print("Handling request in RealSubject")
class Proxy:
def __init__(self):
self._real_subject = None
def request(self):
if self._real_subject is None:
print("Creating RealSubject")
self._real_subject = RealSubject()
print("Proxy delegating to RealSubject")
self._real_subject.request()
proxy = Proxy()
proxy.request()
proxy.request()
These patterns help build systems that are easier to understand, test, and maintain by breaking down large components into smaller ones.
Patterns like Adapter and Bridge allow components to be used interchangeably even if they are incompatible by default.
Patterns like Flyweight and Composite allow reuse of component logic efficiently.
Identify your problem type (interface incompatibility, control access, complexity, etc.) and select a structural pattern that fits best.
Favor object composition to combine behaviors dynamically as needed, especially with patterns like Decorator and Composite.
Keep pattern logic encapsulated to ensure each class has a single responsibility.
Structural design patterns provide powerful solutions to organizing and composing objects and classes. By leveraging Adapter, Bridge, Composite, Decorator, Facade, Flyweight, and Proxy, Python developers can write cleaner, modular, and more maintainable code. These patterns address different problems β from simplifying complex APIs to minimizing memory usage and ensuring better object collaboration.
Understanding and applying these patterns allows developers to build systems that are easier to extend, test, and evolve over time.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved