Sobes.tech
Middle+

What are structural design patterns?

sobes.tech AI

Answer from AI

Structural design patterns describe how classes and objects can be combined to form larger structures. They help organize interactions between objects, making the system more flexible and maintainable.

Some common structural patterns:

  • Adapter: Allows classes with incompatible interfaces to work together.
  • Bridge: Separates an abstraction from its implementation, allowing them to vary independently.
  • Composite: Treats a group of objects as a single object.
  • Decorator: Adds new behavior to objects dynamically without altering their code.
  • Facade: Provides a unified interface to a set of interfaces in a subsystem.
  • Flyweight: Saves memory by sharing common state between many small objects.
  • Proxy: Acts as a substitute for another object to control access to it.

Example of using the Decorator pattern:

# Base component
class Coffee:
    def cost(self):
        return 5

    def description(self):
        return "Regular coffee"

# Base decorator
class CoffeeDecorator:
    def __init__(self, coffee):
        self._coffee = coffee

    def cost(self):
        return self._coffee.cost()

    def description(self):
        return self._coffee.description()

# Concrete decorator
class MilkDecorator(CoffeeDecorator):
    def cost(self):
        return self._coffee.cost() + 2

    def description(self):
        return self._coffee.description() + ", with milk"

# Usage
my_coffee = Coffee()
print(my_coffee.description(), "-", my_coffee.cost()) # Regular coffee - 5

coffee_with_milk = MilkDecorator(my_coffee)
print(coffee_with_milk.description(), "-", coffee_with_milk.cost()) # Regular coffee, with milk - 7

These patterns provide flexibility through object composition instead of inheritance, allowing changes to be made to the system without modifying existing code.