Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.

Similar presentations


Presentation on theme: "The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1."— Presentation transcript:

1 The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1

2 Motivating Example (Bob Tarr) Suppose that you have a GUI component such as a TextView, and you want to be able to add different kinds of properties such as borders and scrollbars. Assume the you have three types of borders (e.g., plain, fancy, and 3D) and two types of scrollbars (horizontal and vertical). Not every TextView object needs a border or a scrollbar, and a TextView object might need only one scrollbar, but not both. How can we design a solution that provides the flexibility to add borders and scrollbars? ©SoftMoore ConsultingSlide 2

3 Motivating Example (continued) Solution 1: Use inheritance. Inheritance is a static (compile-time) property. In order to provide a solution using inheritance, we would need class TextView plus 15 subclasses. –TextViewWithPlainBorder –TextViewWithFancyBorder –... –TextViewWith3DBorderVerticalHorizontalScrollbar Problems with Solution 1 –explosion of subclasses –choice of subclass to instantiate must be made at compile time –What if there were another type of behavior to TextView? ©SoftMoore ConsultingSlide 3

4 Motivating Example (continued) Solution 2: Use the Strategy pattern. Design the TextView class so that it can have different types of borders and scrollbars. This approach would not have the problems associated with Solution 1 –no class explosion –borders and/or scrollbars could be added at run-time. –easy to add new types of borders or variations on scrollbars (e.g., thin versus normal) ©SoftMoore ConsultingSlide 4

5 Motivating Example (continued) public class TextView extends Component { private Border border; private Scrollbar vsb; private Scrollbar hsb; public TextView(Border border, Scrollbar vsb, Scrollbar hsb) { this.border = border; this.vsb = vsb; this.hsb = hsb; } ©SoftMoore ConsultingSlide 5 (continued on next slide)

6 Motivating Example (continued) public TextView() { this(null, null, null); }... // set methods for borders and scrollbars ©SoftMoore ConsultingSlide 6 (continued on next slide)

7 Motivating Example (continued) public void draw() { if (border != null) border.draw(); if (vsb ! = null) vsb.draw(); if (hsb ! = null) hsb.draw();... // code to draw the TextView object } ©SoftMoore ConsultingSlide 7

8 Motivating Example (continued) Problem with Solution 2: Class TextView was modified so that it knew about borders and scrollbars. We could add different flavors of borders and scrollbars, but no other type of behavior; i.e., the types of behaviors that could be added to TextView were fixed at compile-time. If we wanted to add another type of behavior in addition to borders or scrollbars, we would need to modify TextView again. ©SoftMoore ConsultingSlide 8

9 Motivating Example (continued) Solution 3: Use the Decorator pattern. Instead of adding behaviors such as borders and scrollbars to a TextView object, using the decorator pattern you wrap the TextView object in one or more Decorator objects, and use those objects in the application. In effect, you add the TextView to its decorators. The TextView class knows nothing about its decorator objects, which makes it easy to add new types of behaviors to a TextView. ©SoftMoore ConsultingSlide 9

10 Motivating Example (continued) ©SoftMoore ConsultingSlide 10 Component TextView Structure of Solution 3 Decorator BorderScrollbar 1 PlainBorderFancyBorderThreeDBorderHScrollbarVScrollbar

11 Motivating Example (continued) public class TextView extends Component { public void draw() {... // code to draw the TextView object } ©SoftMoore ConsultingSlide 11 TextView knows nothing about borders and scrollbars.

12 Motivating Example (continued) public class FancyBorder extends Decorator { private Component component; public FancyBorder(Component component) { this.component = component; } public void draw() { component.draw(); // code to draw the FancyBorder } ©SoftMoore ConsultingSlide 12 Decorators need to know about components.

13 Motivating Example (continued) public class Client { public static void main(String[] args) { TextView plainTv = new TextView(); Component fbTv = new FancyBorder(plainTv); Component vsTv = new VScrollbar(fbTv); Component tv = new HScrollbar(vsTv); } ©SoftMoore ConsultingSlide 13 Client creates a plain TextView object and wraps it in the desire Decorator objects.

14 Strategy versus Decorator The Strategy pattern changes the “guts” of an object. –create component object –add strategy to component (component knows about its strategy) –client uses the component The Decorator pattern changes the “skin” of an object. –create component object –create decorator and add component to decorator (component does not know about its decorator) –client uses the decorator ©SoftMoore ConsultingSlide 14 : Client: Component: Strategy : Client: Decorator : Component

15 Decorator Pattern Intent: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. Also Known As: Wrapper Applicability: Use the Decorator pattern –to add responsibilities to individual objects dynamically and transparently, that is, 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. Slide 15©SoftMoore Consulting

16 Decorator Pattern (continued) ©SoftMoore ConsultingSlide 16 1 Structure Component operation() ConcreteComponent operation() Decorator operation() ConcreteDecoratorA addedState operation() ConcreteDecoratorB operation() addedOperation()

17 Decorator Pattern (continued) Participants Component –defines the interface for objects that can have responsibilities added to them dynamically. ConcreteComponent –defines an object to which additional responsibilities can be attached. Decorator –maintains a reference to a Component object and defines an interface that conforms to Component’s interface. ConcreteDecorator –adds responsibilities to the component. Slide 17©SoftMoore Consulting

18 Decorator Pattern (continued) Collaborations Decorator forwards requests to its Component object. It may optionally perform additional operations before and after forwarding the request ©SoftMoore ConsultingSlide 18

19 Decorator Pattern (continued) Consequences (two benefits and two liabilities) The Decorator pattern provides a flexible alternative to inheritance. Whereas inheritance lets you add functionality to classes at compile time, decorators let you add functionality to objects at runtime Decorators you to add functionality incrementally as needed. An application doesn’t incur a penalty for features it doesn’t use. A decorator and its component aren’t identical. Don’t rely on object identity when using decorators. Decorators often results in lots of little objects. ©SoftMoore ConsultingSlide 19

20 Decorator Pattern (continued) Implementation A decorator object’s interface must conform to the interface of the component it decorates. There is no need to define an abstract decorator class when you need to add only one responsibility; e.g., when you are dealing with an existing class hierarchy rather than designing a new one. Just put the responsibility in the concrete Decorator. ©SoftMoore ConsultingSlide 20

21 Decorator Pattern (continued) Implementation (continued) To ensure a conforming interface, components and decorators must subclass a common Component class. It is important to keep this common class lightweight; otherwise the complexity of the Component class might make the decorators too heavyweight to use in quantity. Strategy might be a better choice than Decorator in situations where the Component class is intrinsically heavyweight. ©SoftMoore ConsultingSlide 21

22 Decorator Pattern in Java: Swing Java’s Swing GUI classes use decorators in a manner very similar to that described in the motivating example. Example 1 (from The Swing Tutorial) //In a container that uses a BorderLayout: JTextArea = new JTextArea(5, 30);... JScrollPane scrollPane = new JScrollPane(textArea);... add(scrollPane, BorderLayout.CENTER); Example 2 (David Geary) TableSortDecorator sortDecorator = new TableSortDecorator(table.getModel); table.setModel(sortDecorator); ©SoftMoore ConsultingSlide 22

23 Decorator Pattern in Java: I/O Basic I/O classes in Java provide minimal functionality. –classes InputStream and OutputStream for byte streams –classes Reader and Writer for character streams Additional behaviors can be added to an existing stream using the decorator pattern. –buffered stream –data stream (I/O of primitive types) –pushback stream (undo a read operation) The constructors for the byte stream classes take other byte streams as parameters, and similarly for the character stream classes. ©SoftMoore ConsultingSlide 23

24 Decorator Pattern in Java: I/O (continued) // create a basic file reader FileReader fRdr = new FileReader(data.txt); // add buffering and method readLine() // (uses a default-sized input buffer) BufferedReader bRdr = new BufferedReader(fRdr); // add capability to "unread" a character // or an array of characters PushbackReader pbRdr = new PushbackReader(bRdr); // add line numbers and method getLineNumber() LineNumberReader lnRdr = new LineNumberReader(pbRr);... // read data using lnRdr ©SoftMoore ConsultingSlide 24

25 Related Patterns A decorator is different from an adapter in that a decorator only changes an objects responsibilities, not its interface (but it can add to the interface). A decorator can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities and isn’t intended for object aggregation. A decorator lets you change the “skin” of an object. A strategy lets you change its “guts”. ©SoftMoore ConsultingSlide 25

26 References Decorator pattern (Wikipedia) http://en.wikipedia.org/wiki/Decorator_pattern Decorate your Java Code by David Geary (JavaWorld) http://www.javaworld.com/article/2075920/core-java/decorate-your-java-code.html Tutorial: Avoid Excessive Subclassing with the Decorator Design Pattern (Burd and Redlich) http://www.redlich.net/pdf/publications/jupitermedia/decorator.pdf ©SoftMoore ConsultingSlide 26


Download ppt "The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1."

Similar presentations


Ads by Google