Junior — Middle
What is the difference between using Decorator and Adapter patterns in system design?
sobes.tech AI
Answer from AI
The Decorator and Adapter patterns solve different design problems:
-
Decorator
- Allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects.
- Used to extend functionality without modifying the original class.
- Example: adding logging or caching to an existing object.
-
Adapter
- Enables objects with incompatible interfaces to work together.
- Wraps one interface into another expected by the client.
- Used for integrating third-party libraries or legacy code with a new interface.
In summary:
- Decorator extends the behavior of an object.
- Adapter changes the interface of an object.
Example in C#:
// Adapter
interface ITarget { void Request(); }
class Adaptee { public void SpecificRequest() { } }
class Adapter : ITarget {
private Adaptee adaptee = new Adaptee();
public void Request() { adaptee.SpecificRequest(); }
}
// Decorator
interface IComponent { void Operation(); }
class ConcreteComponent : IComponent {
public void Operation() { /* base implementation */ }
}
class Decorator : IComponent {
protected IComponent component;
public Decorator(IComponent component) { this.component = component; }
public virtual void Operation() {
component.Operation();
// additional behavior
}
}