Junior — Middle
Can you give an example of using the structural pattern in software system design?
sobes.tech AI
Answer from AI
Structural design patterns help organize relationships between classes and objects to simplify the system structure.
Example: the "Decorator" pattern.
It allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects without changing the original class.
Example in Java:
// Component interface
interface Coffee {
double cost();
String ingredients();
}
// Concrete component
class SimpleCoffee implements Coffee {
public double cost() { return 1.0; }
public String ingredients() { return "Coffee"; }
}
// Decorator
class MilkDecorator implements Coffee {
private Coffee coffee;
public MilkDecorator(Coffee coffee) { this.coffee = coffee; }
public double cost() { return coffee.cost() + 0.5; }
public String ingredients() { return coffee.ingredients() + ", Milk"; }
}
// Usage
Coffee coffee = new MilkDecorator(new SimpleCoffee());
System.out.println(coffee.cost()); // 1.5
System.out.println(coffee.ingredients()); // Coffee, Milk
This approach allows flexible extension of functionality without modifying existing code.