Ultimate Design Patterns - Structural Flashcards
What problem does the Composite Pattern solve?
Allows us to work with objects or groups as if they were the same
without having to use Object base class and explicitly cast objects to types
When do we use the Composite Pattern?
Want to represent a hierarchy and treat the objects in hieararchy in the same way (parts and containers)
Ex. Files and Folders
How can we implement the Component Pattern?
Allows us to represents object hierarchies where individual objects and compositions of objects are treated the same way
What’s an excercise using the Composite Pattern?
Represents object hierarchies where individual objects and compositions of objects are treated the same way.
AP What is the Adapter Pattern?
Allows converting the interface of a class into another interface that clients expect.
Just like an electricity adapter converts plug to format!
Ex. Apply various filters to a photo
What real world problem does the Adapter Pattern Solve?
We have a class that we want to use but the interface doesn’t match form we expect
Adapter pattern converts interface of the class to the proper form
We have a third party filter library that doesn’t implement Filter Interface
Our viewImage class only accepts filters that Implement Filter Interface
Adapter Pattern allows us to change third party filter Interface to match required form for viewImage (Filter Interface)
How do we implement the Adapter Pattern using composition?
Favor composition over inheritance!
How do we implement the Adapter Pattern using inheritance?
Not the favorable approach!
Why?
It is less flexible than composition
What is an excercise using the Adapter Pattern?
What problem does the Decorator Pattern solve?
Allows us to add additional behavior to an object dynamically
Why?
For every feature we are adding, have to create various classes to combine features.
With five features, would have to create many classes to combine features!
This isn’t extensible approach.
Ex. We can create a CloudStream object and decorate it with additional behavior
What is the Decorator Pattern?
Allows us to add additional behavior to an existing object
What is an old saying?
Favor composition over inheritence!
Why?
It doesn’t mean inheritance is bad, it’s a great solution to many problems but not this problem
What is similar and different between the Decorator Pattern and the Adapter Pattern?
Both pattern implementation uses composition relationship
Adapter Pattern - We change the interface to a different form
Decorater Pattern - We add additional behavior to an object
How do we implement the Decorator Pattern?
Allows us to add additional operations to an object
How?
Decorator - a wrapper class with additional operations composed of an object
What is an excercise using the Decorator Pattern?