Decorator Pattern

Decorator pattern is used to add responsibilities to individual objects, instead of to entire class. The decorator abstract class has the same interface as component class, and forward the invocation to its component object. The concrete decorator class will add some additional features to its components.

UML Graph: (from NetBeans 6.1)

UML Graph Decorator

Applicability: (from GoF)

  •  to add responsibilities to individual objects dynamically and transparently, that i, without affecting other objects.
  • for responsibilities that can be withdrawn
  • when extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.

Consequences:

  1. More flexibility than static inheritance.
  2. Avoids feature-laden classes high up in the hierarchy.
  3. A decorator and its component aren't identical.
  4.  Lots of little objects.

Some Notes:

InputStream in java.io is a typical application of Decorator pattern. The essential component is InputStream, like FileInputStream, ByteArrayInputStream. And you can decorate these components with decorators, such as InputStreamReader, BufferedReader.

Here's an example:

new LineNumberReader(new BufferedReader(new InputStreamReader(socket.getInputStream())));

Posted in 设计模式 | Tagged | Leave a comment