L10: Structuring relationships in a system Flashcards
Decorator: Aim, what it does, what is it used for
A decorator aims to customize objects at runtime.
Attach additional functionalities to an object:
- Note: to an object (at runtime, not all objects), not a class (at design time)
- Allows to adhere to separation of concerns / single responsibility principle and the open-closed principle.
Used for:
- Adapting GUI elements on demand
- I/O operations
E.g.: LineNumberReader read = new LineNumberReader(new FileReader(file));
What does the decorator essentially do?
Promotes composition to extend an object’s functionality
We do so by wrapping new functionality around an existing object.
What is the diamond problem?
In multiple inheritance, it can be unclear what super method to call.
Being careful with the decorator
- Added behavior can interact (unintentionally)
- Complex hierarchies and nested structures can complicate comprehension
- Overheads in performance, code, maintenance, …
- Checking for object identity is complicated
instanceof
Instanceof tests whether an object is of a specific type (important to use before casting an object into another type).
Switch can also be used instead of Instanceof
Facade: what does it provide, what does it do, what is it used for
A facade provides an unified interface for a unit.
Hide the implementation of a larger unit behind one interface
- Define a single access point
- Hide the complexity of a larger unit
- Put contraints on the order of method calls
- Decouple the system (Minimise Coupling, Maximise Cohesion)
Used for
- Any API
- SwingWorker
Being careful with the facade
The facade aims to implement many good design principles.
There are some things to keep in mind:
- Hiding details of the underlying system can also complicate its use
- The facade must also be maintained
- If not used appropriately, it can introduce unnecessary complexity
- As for any design pattern: Do not overuse, make sure it actually improves your software design! (hammer and nail topic)