0% found this document useful (0 votes)
5 views

5-design-patterns-java-structural-m5-slides

The Decorator Pattern, also known as a wrapper, allows for adding behavior to objects without affecting others, emphasizing composition over inheritance. It adheres to the Single Responsibility Principle and is commonly used in Java's InputStream and Collections. However, it can lead to complexity and confusion with simple inheritance, requiring careful implementation to avoid pitfalls like creating too many classes for features.

Uploaded by

podam91581
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

5-design-patterns-java-structural-m5-slides

The Decorator Pattern, also known as a wrapper, allows for adding behavior to objects without affecting others, emphasizing composition over inheritance. It adheres to the Single Responsibility Principle and is commonly used in Java's InputStream and Collections. However, it can lead to complexity and confusion with simple inheritance, requiring careful implementation to avoid pitfalls like creating too many classes for features.

Uploaded by

podam91581
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Decorator Pattern

Bryan Hansen
twitter: bh5k | http://www.linkedin.com/in/hansenbryan
Concepts
▪ Also called a wrapper
▪ Add behavior without affecting others
▪ More than just inheritance
▪ Single Responsibility Principle
▪ Compose behavior dynamically
▪ Examples:
▪ java.io.InputStream
▪ java.util.Collections#checkedList
▪ UI components
Design

Inheritance based
Utilizes composition and inheritance (is-a,
has-a)
Alternative to subclassing
Constructor requires instance from hierarchy
UML
Everyday Example - InputStream
File  file  =  new  File("./output.txt");  
file.createNewFile();  
     
OutputStream  oStream  =  new  FileOutputStream(file);  
     
DataOutputStream  doStream  =  new  DataOutputStream(oStream);  
doStream.writeChars("text");
Exercise Decorator

Component, ConcreteComponent,
Decorator, ConcreteDecorator
Create Decorator
Implement another Decorator
Not a Creational Pattern
Pitfalls
▪ New class for every feature added
▪ Multiple little objects
▪ Often confused with simple inheritance
Contrast

Composite Decorator
▪ Tree structure ▪ Contains another entity
▪ Leaf and Composite have same ▪ Modifies behavior (adds)
interface ▪ Doesn’t change underlying object
▪ Unity between objects
Decorator Summary

• Original object can stay the same


• Unique way to add functionality
• Confused with inheritance
• Can be more complex for clients

You might also like