How does the Decorator pattern support OCP?
Answer
The Decorator pattern is a textbook implementation of OCP. It adds behavior to an object dynamically without modifying its class. Both the decorator and the decorated object implement the same interface. Example: a Logger interface implemented by ConsoleLogger. To add timestamping, create TimestampLogger(Logger wrapped) that adds a timestamp before delegating to the wrapped logger. To add encryption, create EncryptedLogger(Logger wrapped). You can compose these at runtime: new EncryptedLogger(new TimestampLogger(new ConsoleLogger())). Neither the original ConsoleLogger nor any previous decorator is modified when new behavior is added. Laravel's middleware pipeline, Java I/O streams, and many plugin systems use the Decorator pattern.
Previous
How do you apply SOLID in a legacy codebase?
Next
What is "interface pollution" and which principle prevents it?
More SOLID Principles Questions
View all →- Intermediate How would you refactor a class that violates SRP?
- Intermediate How does the Strategy pattern support OCP?
- Intermediate What are the conditions for LSP compliance?
- Intermediate How does ISP prevent "fat interfaces"?
- Intermediate What is the difference between DIP and dependency injection containers?