Suggest an editImprove this articleRefine the answer for “What is the essence of the Decorator pattern?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**Decorator** is a **structural pattern** that lets you **dynamically add new behavior to an object** without changing its class and without breaking the open/closed principle (OCP). **Key point:** a decorator wraps an object in another object that implements the same interface but adds behavior before or after calling the original methods.Shown above the full answer for quick recall.Answer (EN)Image**Decorator** is a **structural pattern** that lets you **dynamically add new behavior to an object** without changing its class and without breaking the open/closed principle (OCP). --- ### 1. **The Core Idea** Instead of creating many subclasses to extend functionality, a decorator **wraps an object in another object** that implements the same interface, but adds extra behavior *before or after* calling the original methods. --- ### 2. **When to Use It** - When you need to **extend an object's behavior at runtime**, rather than at inheritance time. - When it is impossible or undesirable to change the source code of the class (for example, it comes from a third-party library). - When you need to **combine several features** without causing an explosion of subclasses. --- ### 3. **Example (Java)** ```java interface DataSource { void write(String data); } class FileDataSource implements DataSource { public void write(String data) { System.out.println("Writing to file: " + data); } } class EncryptionDecorator implements DataSource { private DataSource wrappee; public EncryptionDecorator(DataSource source) { this.wrappee = source; } public void write(String data) { data = encrypt(data); wrappee.write(data); } private String encrypt(String data) { return "Encrypted(" + data + ")"; } } ``` Usage: ```java DataSource source = new EncryptionDecorator(new FileDataSource()); source.write("Hello"); ``` Result: `FileDataSource` works as before, but now the data is encrypted before being written. --- ### 4. **Advantages** - Behavior can be **added dynamically**, without changing the source class. - You can **combine several decorators** (logging + compression + encryption). - Supports the principle of **composition over inheritance**. --- ### 5. **Summary** **Decorator** is a way to "put extra features on" an object, while leaving its interface unchanged. It turns rigid inheritance into a **flexible, dynamic extension of behavior**.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.