2IRR00 · Topic 10
Structural Patterns
Decorator, Facade, and comparing in Java
Decorator
Decorator attaches additional responsibilities to an OBJECT at runtime (not a class at design time) by wrapping it, as a flexible alternative to inheritance.
Supports single-responsibility (split concerns into decorators) and open/closed (add behaviour without modifying the class).
Structure: an abstract Component, a ConcreteComponent, an abstract Decorator that HAS-A Component (aggregation), and ConcreteDecorators that add behaviour before/after delegating to the wrapped component.
Wrapping order can matter: new DashedBorder(new BlueBorder(new Rectangle())).
Real example: Java I/O streams — new LineNumberReader(new FileReader(file)).
Shape s = new DashedBorder(new BlueBorder(new Rectangle()));
s.draw(); // adds dashed + blue around the rectangle
// Java I/O:
LineNumberReader r = new LineNumberReader(new FileReader(file));Common mistakes
- Thinking decorator changes a class — it decorates an OBJECT at runtime.
- Object identity: a decorated object != the base (rect == dashedRect is false) — needs custom equals()/hashCode() to compare base shapes.
Exam tips
- Decorator = add behaviour to an object at runtime via composition (alternative to deep inheritance / diamond problem).
- It uses aggregation (the wrapped part can exist without the decorator).
Decorator practice
1 questions
Facade & comparing in Java
Facade provides a single unified interface that hides the complexity of a larger unit/subsystem; comparing in Java uses == (reference) vs equals() (content).
Facade: one access point, hides complexity, can constrain the order of calls, decouples the system. Used for any API/library wrapper; SwingWorker itself is a facade over Thread/Runnable.
Facade vs Blob: a facade only defines a minimal interface and delegates (no behaviour of its own); a blob/god class concentrates behaviour and data.
Comparing: == compares reference equality for objects; equals() compares content (override it for your own types, and also override hashCode() consistently). instanceof tests type before casting.
String a = "abc", b = "abc", c = new String("abc");
a == b; // true (string pool, same object)
a == c; // false (different object)
a.equals(c); // true (same content)Common mistakes
- Confusing a facade (minimal interface, delegates) with a blob (does everything).
- Using == to compare object content; overriding equals() without hashCode().
Exam tips
- Facade = unified interface hiding a subsystem; a singleton facade ensures one access point.
- == reference vs equals() content; override both equals and hashCode together.
Facade & comparing in Java practice
1 questions