Python - Structural Design Patterns

Python - Structural Design Patterns

Structural Design Patterns in Python

Introduction

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:

  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Facade
  • Flyweight
  • Proxy

Adapter Pattern

Overview

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.

Use Case

  • Integrating legacy code with a modern interface
  • Bridging different APIs

Example

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())

Bridge Pattern

Overview

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.

Use Case

  • Decouple high-level logic from platform-specific code
  • Support multiple variants without class explosion

Example

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()

Composite Pattern

Overview

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.

Use Case

  • Graphics systems
  • UI components

Example

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()

Decorator Pattern

Overview

The Decorator pattern allows behavior to be added to individual objects dynamically, without affecting the behavior of other objects from the same class.

Use Case

  • Adding responsibilities to objects
  • Implementing features like logging, access control

Example

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())

Facade Pattern

Overview

The Facade pattern provides a unified interface to a set of interfaces in a subsystem, making the subsystem easier to use.

Use Case

  • Simplifying complex systems
  • Creating wrappers for third-party APIs

Example

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()

Flyweight Pattern

Overview

The Flyweight pattern reduces memory usage by sharing common parts of object state between multiple objects instead of storing all data in each object.

Use Case

  • Large number of similar objects (e.g. in a game or text editor)

Example

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")

Proxy Pattern

Overview

The Proxy pattern provides a surrogate or placeholder for another object to control access to it.

Use Case

  • Access control
  • Lazy initialization
  • Logging, monitoring

Example

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()

Benefits of Structural Patterns

Modularity

These patterns help build systems that are easier to understand, test, and maintain by breaking down large components into smaller ones.

Interchangeability

Patterns like Adapter and Bridge allow components to be used interchangeably even if they are incompatible by default.

Code Reuse

Patterns like Flyweight and Composite allow reuse of component logic efficiently.

Best Practices

Choose the Right Pattern

Identify your problem type (interface incompatibility, control access, complexity, etc.) and select a structural pattern that fits best.

Use Composition over Inheritance

Favor object composition to combine behaviors dynamically as needed, especially with patterns like Decorator and Composite.

Encapsulation and Separation of Concerns

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.

Beginner 5 Hours
Python - Structural Design Patterns

Structural Design Patterns in Python

Introduction

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:

  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Facade
  • Flyweight
  • Proxy

Adapter Pattern

Overview

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.

Use Case

  • Integrating legacy code with a modern interface
  • Bridging different APIs

Example

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())

Bridge Pattern

Overview

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.

Use Case

  • Decouple high-level logic from platform-specific code
  • Support multiple variants without class explosion

Example

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()

Composite Pattern

Overview

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.

Use Case

  • Graphics systems
  • UI components

Example

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()

Decorator Pattern

Overview

The Decorator pattern allows behavior to be added to individual objects dynamically, without affecting the behavior of other objects from the same class.

Use Case

  • Adding responsibilities to objects
  • Implementing features like logging, access control

Example

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())

Facade Pattern

Overview

The Facade pattern provides a unified interface to a set of interfaces in a subsystem, making the subsystem easier to use.

Use Case

  • Simplifying complex systems
  • Creating wrappers for third-party APIs

Example

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()

Flyweight Pattern

Overview

The Flyweight pattern reduces memory usage by sharing common parts of object state between multiple objects instead of storing all data in each object.

Use Case

  • Large number of similar objects (e.g. in a game or text editor)

Example

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")

Proxy Pattern

Overview

The Proxy pattern provides a surrogate or placeholder for another object to control access to it.

Use Case

  • Access control
  • Lazy initialization
  • Logging, monitoring

Example

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()

Benefits of Structural Patterns

Modularity

These patterns help build systems that are easier to understand, test, and maintain by breaking down large components into smaller ones.

Interchangeability

Patterns like Adapter and Bridge allow components to be used interchangeably even if they are incompatible by default.

Code Reuse

Patterns like Flyweight and Composite allow reuse of component logic efficiently.

Best Practices

Choose the Right Pattern

Identify your problem type (interface incompatibility, control access, complexity, etc.) and select a structural pattern that fits best.

Use Composition over Inheritance

Favor object composition to combine behaviors dynamically as needed, especially with patterns like Decorator and Composite.

Encapsulation and Separation of Concerns

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.

Frequently Asked Questions for Python

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.


Python's syntax is a lot closer to English and so it is easier to read and write, making it the simplest type of code to learn how to write and develop with. The readability of C++ code is weak in comparison and it is known as being a language that is a lot harder to get to grips with.

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. Performance: Java has a higher performance than Python due to its static typing and optimization by the Java Virtual Machine (JVM).

Python can be considered beginner-friendly, as it is a programming language that prioritizes readability, making it easier to understand and use. Its syntax has similarities with the English language, making it easy for novice programmers to leap into the world of development.

To start coding in Python, you need to install Python and set up your development environment. You can download Python from the official website, use Anaconda Python, or start with DataLab to get started with Python in your browser.

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.

Python alone isn't going to get you a job unless you are extremely good at it. Not that you shouldn't learn it: it's a great skill to have since python can pretty much do anything and coding it is fast and easy. It's also a great first programming language according to lots of programmers.

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

  • Choose Your Focus. Python is a versatile language with a wide range of applications, from web development and data analysis to machine learning and artificial intelligence.
  • Practice regularly.
  • Work on real projects.
  • Join a community.
  • Don't rush.
  • Keep iterating.

The following is a step-by-step guide for beginners interested in learning Python using Windows.

  • Set up your development environment.
  • Install Python.
  • Install Visual Studio Code.
  • Install Git (optional)
  • Hello World tutorial for some Python basics.
  • Hello World tutorial for using Python with VS Code.

Best YouTube Channels to Learn Python

  • Corey Schafer.
  • sentdex.
  • Real Python.
  • Clever Programmer.
  • CS Dojo (YK)
  • Programming with Mosh.
  • Tech With Tim.
  • Traversy Media.

Python can be written on any computer or device that has a Python interpreter installed, including desktop computers, servers, tablets, and even smartphones. However, a laptop or desktop computer is often the most convenient and efficient option for coding due to its larger screen, keyboard, and mouse.

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.

  • Google's Python Class.
  • Microsoft's Introduction to Python Course.
  • Introduction to Python Programming by Udemy.
  • Learn Python - Full Course for Beginners by freeCodeCamp.
  • Learn Python 3 From Scratch by Educative.
  • Python for Everybody by Coursera.
  • Learn Python 2 by Codecademy.

  • Understand why you're learning Python. Firstly, it's important to figure out your motivations for wanting to learn Python.
  • Get started with the Python basics.
  • Master intermediate Python concepts.
  • Learn by doing.
  • Build a portfolio of projects.
  • Keep challenging yourself.

Top 5 Python Certifications - Best of 2024
  • PCEP (Certified Entry-level Python Programmer)
  • PCAP (Certified Associate in Python Programmer)
  • PCPP1 & PCPP2 (Certified Professional in Python Programming 1 & 2)
  • Certified Expert in Python Programming (CEPP)
  • Introduction to Programming Using Python by Microsoft.

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.

The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python website, https://www.python.org/, and may be freely distributed.

If you're looking for a lucrative and in-demand career path, you can't go wrong with Python. As one of the fastest-growing programming languages in the world, Python is an essential tool for businesses of all sizes and industries. Python is one of the most popular programming languages in the world today.

line

Copyrights © 2024 letsupdateskills All rights reserved