Design Patterns Java™ Workbook

(Michael S) #1
Chapter 12. Chain of Responsibility

Anchoring a Chain......................................................................................................................................


When you write the getResponsible() method for MachineComponent, you have to
consider that a MachineComponent object's parent might be null. Alternatively, you can
tighten up your object model, insisting that MachineComponent objects have a non-null
parent. To achieve this, add a parent argument to the constructor for MachineComponent.
(You may want to throw an exception if the supplied object is null.) Also consider that an
object will be the root—a distinguished object that has no parent. A reasonable approach is to
create a MachineRoot class as a subclass of MachineComposite (not
MachineComponent). Then you can guarantee that a MachineComponent object always
has a responsible engineer if



  • The constructor(s) for MachineRoot require an Engineer object

  • The constructor(s) for MachineComponent require a non-null parent object that is
    itself a MachineComponent

Free download pdf