Instructor: Stefan Mitsch
Requirements
EmailNotifier
Decorator adds functionality to an object dynamically
Problem illustration: want to add and remove functionality at runtime.
How to extend an object without subclassing?
Problem
Intent
Structure
The Component interface declares operations that are common to both wrappers and wrapped objects
Component
The ConcreteComponent is a class of objects being wrapped; it defines basic behavior, which can be extended by decorators.
ConcreteComponent
The Decorator class references the wrapped object
Decorator
The ConcreteDecorator classes define extra behavior that can be added to the wrapped object dynamically; concrete decorators execute their additional behavior either before or after the base behavior
ConcreteDecorator
The Client sets up of layers of decorators
Client
Add multiple layers of clothing to improve insulation Image from "Dive into Design Patterns"
// common interface for object and decorators public interface Character { void getStrength(); } // primary object public class BaseCharacter { private int strength; } // decorator class public abstract class CharacterDecorator { private Character wrappee; public CharacterDecorator(Character wrappee) { this.wrappee = wrappee; } public int getStrength() { return wrappee.getStrength(); } } // concrete decorators public class Shield extends CharacterDecorator { private int strength; public int getStrength() { return strength + super.getStrength(); } } public class Sword extends CharacterDecorator { /*...*/ }
interface
Code Smell: Code provides an embellishment to a class's core responsibility
Before: Conditional code
Composite
Strategy