Docsity

Design Patterns: Decorator, Template Method, and Observer, Papers of Programming Languages

Toggle sidebar
bg1
77
CMSC 433 – Programming Language
Technologies and Paradigms
Spring 2004
Design Patterns
February 24, 2004
78
Decorator Pattern: Features
•Decorator conforms to interface of decorated
component
–Its presence is transparent to the component's clients.
•Decorator forwards requests to encapsulated
component
–May perform additional actions before or after
•Can nest decorators recursively
–Allows unlimited added responsibilities
•Can add/remove responsibilities dynamically
79
Structure
80
Decorator Pattern Analysis
•Advantages
–Fewer classes than with static inheritance
–Dynamic addition/removal of decorators
–Keeps root classes simple
•Disadvantages
–Proliferation of run-time instances
–Abstract Decorator must provide common interface
• Tradeoffs:
–Useful when components are lightweight
–Otherwise use Strategy
81
Decorator vs. Adapter
•A decorator adds to the responsibilities of an
object
–Usually has the same interface plus more features
•An adapter changes the interface
–But usually not the responsibilities
82
Template Method Pattern
• Problem
–You’re building a reusable class
–You have a general approach to solving a problem,
–But each subclass will do things differently
•Solution
–Invariant parts of an algorithm in parent class
–Encapsulate variant parts in template methods
–Subclasses override template methods
–At runtime template method invokes subclass ops
pf3
pf4
pf5

Partial preview of the text

Download Design Patterns: Decorator, Template Method, and Observer and more Papers Programming Languages in PDF only on Docsity!

77

CMSC 433 – Programming Language

Technologies and Paradigms

Spring 2004

Design Patterns

February 24, 2004

78

Decorator Pattern: Features

• Decorator conforms to interface of decorated

component

  • Its presence is transparent to the component's clients.

• Decorator forwards requests to encapsulated

component

  • May perform additional actions before or after

• Can nest decorators recursively

  • Allows unlimited added responsibilities

• Can add/remove responsibilities dynamically

79

Structure

80

Decorator Pattern Analysis

• Advantages

  • Fewer classes than with static inheritance
  • Dynamic addition/removal of decorators
  • Keeps root classes simple

• Disadvantages

  • Proliferation of run-time instances
  • Abstract Decorator must provide common interface

• Tradeoffs:

  • Useful when components are lightweight
  • Otherwise use Strategy

Decorator vs. Adapter

• A decorator adds to the responsibilities of an

object

  • Usually has the same interface plus more features

• An adapter changes the interface

  • But usually not the responsibilities

Template Method Pattern

• Problem

  • You’re building a reusable class
  • You have a general approach to solving a problem,
  • But each subclass will do things differently

• Solution

  • Invariant parts of an algorithm in parent class
  • Encapsulate variant parts in template methods
  • Subclasses override template methods
  • At runtime template method invokes subclass ops

83

Structure

84

Example: JUnit

• Junit uses template methods pattern for run()

package junit.framework; public class TestCase { ... public void run() { setUp(); runTest(); tearDown() } }

• In class example, we subclass TestCase and

override setUp() and tearDown()

85

Observer Pattern

• Problem

  • Dependent must be consistent with master’s state

• Solution structure: Four kinds of objects

  • Abstract subject
    • Maintain list of dependents; notifies them when master changes
  • Abstract observer
    • Define protocol for updating dependents
  • Concrete subject
    • Manage data for dependents; notifies them when master changes
  • Concrete observers
    • Get new subject state upon receiving update message (^86)

Observer Pattern

Use of Observer Pattern

Observer Pattern (cont’d)

• Consequences

  • Low coupling between subject and observers
    • Subject unaware of dependents
  • Support for broadcasting
    • Dynamic addition and removal of observers
  • Unexpected updates
    • No control by the subject on computations by observers

95

State Pattern

• Problem

  • An object is always in one of several known states
  • The state an object is in determines the behavior of

several methods

• Solution

  • Could use if/case statements in each method
  • Better solution: use dynamic dispatch 96

State Pattern Approach

• Encode different states as objects with same

superclass

• To change state, change the state object

• Methods delegate to state object

97

Example – Finite State Machine

class FSM { State state; public FSM(State s) { state = s; } public void move(char c) { state = state.move(c); } public boolean accept() { return state.accept();} } public interface State { State move(char c); boolean accept(); } 98

FSM Example – cont.

class State1 implements State { static State1 instance = new State1(); private State1() {} public State move (char c) { switch (c) { case 'a': return State2.instance; case 'b': return State1.instance; default: throw new IllegalArgumentException(); } } }^ public boolean accept() {return false;} class State2 implements State { static State2 instance = new State2(); private State2() {} public State move (char c) { switch (c) { case 'a': return State1.instance; case 'b': return State1.instance; default: throw new IllegalArgumentException(); } } public boolean accept() {return true;} }

Structure of State Pattern

Instance of State Pattern

101

State Pattern Notes

• Can use singletons for instances of each state class

  • State objects don’t encapsulate (mutable) state, so can

be shared

• Easy to add new states

  • New states can extend the base class, or
  • New states can extend other states
    • Override only selected functions 102

Lexi: Simple GUI-Based Editor

• Lexi is a WYSIWYG editor

  • Supports documents with textual and graphical objects
  • Scroll bars to select portions of the document
  • Be easy to port to another platform
  • Support multiple look-and-feel interfaces

• Highlights several OO design issues

• Case study of design patterns in the design of Lexi

103

Lexi User Interface

104

Design Issues

• Representation and manipulation of document

• Formatting a document

• Adding scroll bars and borders to Lexi windows

• Support multiple look-and-feel standards

  • Motif and Presentation Manager (!)

• Handle multiple windowing systems

• Support user operations

• Advanced features

  • spell-checking and hyphenation

Structure of a Lexi Document

• Goals:

  • Store text and graphics in document
  • Generate visual display
  • Maintain info about location of display elements

• Caveats:

  • Treat different objects uniformly
    • E.g., text, pictures, graphics
  • Treat individual objects and groups of objects

uniformly

  • E.g., characters and lines of text

Structure of a Lexi Document

• Use recursive composition for defining and

handling complex objects

  • Abstract class Glyph for all displayed objects
  • Glyph responsibilities:
    • Know how to draw itself
    • Knows what space it occupies
    • Knows its children and parent
  • Glyph instances can recursively compose other Glyph

instances

113

Strategy Pattern

• Name

  • Strategy (aka Policy)

• Applicability

  • Many related classes differ only in their behavior
  • Many different variants of an algorithm
  • Need to encapsulate algorithmic information 114

Strategy Pattern: Structure

Strategy Pattern: Consequences

• Clear separation of algorithm definition and use

  • Glyphs and formatting algorithms are independent
  • Alternative (many subclasses) is unappealing
    • Proliferation of classes
    • Algorithms cannot be changed dynamically

• Elimination of conditional statements

  • Like State, Template, …
  • Typical in OO programming

Strategy Pattern Consequences (cont’d)

• Clients must be aware of different strategies

  • When initializing objects

• Proliferation of instances at run-time

  • Each Glyph has a strategy object with formatting

information

  • If strategy is stateless, share strategy objects