Docsity

Design Patterns: Flyweight, Iterator, Decorator, Observer, Composite - Prof. Kenneth M. An, Study notes of Computer Science

Partial preview of the text

Download Design Patterns: Flyweight, Iterator, Decorator, Observer, Composite - Prof. Kenneth M. An and more Study notes Computer Science in PDF only on Docsity!

Lecture 17: Design Patterns (part 2)

Kenneth M. Anderson

Object-Oriented Analysis and Design

CSCI 4448/6448 - Spring Semester, 2005

2

Last Lecture

Design Patterns

Background and Core Concepts Examples Singleton, Factory Method, and Adapter

March 8, 2005 © University of Colorado, Boulder, 2005

Goals of Lecture

Cover Additional Design Patterns

State Iterator Flyweight Decorator Observer Composite 4

State

Intent

Allow an object to alter its behavior when its internal state changes

Motivation

TCPConnection example A TCPConnection class must respond to an open operation differently based on its current state: established, closed, listening, etc.

Previous Example

In lecture 12, we saw the State pattern being used in our MessageBuilder example the MessageBuilder would respond differently to timeout events and selection events based on its current state

March 8, 2005 © University of Colorado, Boulder, 2005

State, continued

Collaborations

Context delegates state-specific requests to the current ConcreteState object A context may pass itself as an argument to the State object handling the request Context is the primary interface for clients Either Context or ConcreteState subclasses can decide which state succeeds another and under what circumstances In the MessageBuilder example of Lecture 12, each ConcreteState object returned a pointer to the next state 8

State, continued

Consequences

State localizes state-specific behavior and partitions behavior for different states State makes state transitions explicit State objects can be shared

Example

See the code distributed with Lecture 12 for an example of the State Pattern

March 8, 2005 © University of Colorado, Boulder, 2005

Iterator

Intent

Provide a way to access the elements of an aggregate object (e.g. a collection class) sequentially without exposing its underlying representation

Also Known As

Cursor

Motivation

A collection may have multiple ways of being “traversed”; Iterator lets you keep traversal operations out of the core collection interface 10

Iterator, continued

Applicability

Use the Iterator pattern to access the contents of a collection without exposing its internals to support multiple traversals of collections to provide a uniform interface for traversing different collections

Participants

Iterator defines an interface for accessing and traversing elements ConcreteIterator implements Iterator interface and keeps track of current position within collection Aggregate (Collection Class Interface) defines an interface for creating an Iterator (factory method) ConcreteAggregate (Collection Class) implements the factory method

March 8, 2005 © University of Colorado, Boulder, 2005

Iterator, continued

Implementation

The Iterator interface in the Java Collection classes java.util.Iterator (interface) java.util.List (interface) java.util.LinkedList (class) java.util.ListIterator (interface) implementing subclass is private within List class 14

Flyweight

Intent

Use sharing to support large numbers of fine-grained objects efficiently

Motivation

Imagine a text editor that creates one object per character in a document For large documents, that is a lot of objects! but for simple text documents, there are only 26 letters, 10 digits, and a handful of punctuation marks being referenced by all of the individual character objects

March 8, 2005 © University of Colorado, Boulder, 2005

Flyweight, continued

Applicability

Use flyweight when all of the following are true An application uses a large number of objects Storage costs are high because of the sheer quantity of objects Most object state can be made extrinsic Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed The application does not depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects 16

Flyweight, continued

Participants

Flyweight declares an interface through which flyweights can receive and act on extrinsic state ConcreteFlyweight implements Flyweight interface and adds storage for intrinsic state UnsharedConcreteFlyweight not all flyweights need to be shared; unshared flyweights typically have children which are flyweights FlyweightFactory creates and manages flyweight objects Client maintains extrinsic state and stores references to flyweights

March 8, 2005 © University of Colorado, Boulder, 2005

Flyweight, continued

See code example (released with lecture 13)

Simple implementation of flyweight pattern

Focus is on factory and flyweight rather than on client Demonstrates how to do simple sharing of characters 20

Decorator

Intent

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality

Also Known As

Wrapper

Motivation

Sometimes we want to add responsibilities to individual objects, not to an entire class (like adding scrollbars to windows in GUI toolkits)

March 8, 2005 © University of Colorado, Boulder, 2005

Decorator, continued

Applicability

Use Decorator to add responsibilities to individual objects dynamically for responsibilities that can be withdrawn when extension by subclassing is impractical

Participants

Component defines interface of objects to decorate ConcreteComponent defines an object to decorate Decorator and ConcreteDecorator Decorator maintains a reference to component and defines an interface that conforms to Component’s interface; ConcreteDecorator adds responsibilities to the component

Decorator’s Structure and Roles

22 Component Operation() Concrete Component Operation() Decorator Operation() Concrete DecoratorA AddedState Operation() Concrete DecoratorB AddedState Operation() AddedOperation() component component->Operation() super->Operation() AddedOperation()

March 8, 2005 © University of Colorado, Boulder, 2005

Observer, continued

Applicability

Use Observer when an abstraction has two aspects, one dependent on the other when a change to one object requires changing others when an object should notify objects but should not make assumptions about which objects need to be notified

Participants

Subject provides interface to add and delete observers Observer defines an updating interface for dependants ConcreteSubject stores the state being observed ConcreteObserver stores state that must be consistent with observed state

Observer’s Structure and Roles

26 for all o in observers o->Update() Subject Attach(observer) Detach(observer Notify() Observer Update() observers ConcreteObserver Update() observerState subject ConcreteSubject GetState() SetState() subjectState subject->GetState() ... update observer state ...

March 8, 2005 © University of Colorado, Boulder, 2005

Observer, continued

Collaborations

ConcreteSubject notifies observers whenever it changes its observed state After receiving a notification, ConcreteObserver gets state from ConcreteSubject see sequence diagram on page 295 of Design Patterns 28

Observer, continued

Consequences

Abstract coupling between Subject and Observer Subjects do not know the concrete subclasses of their observers Support for broadcast communication Subject does not know who is listening Unexpected updates Change in state may update an unintended object, one we didn’t suspect was an observer, or should only be observing at well-defined times

March 8, 2005 © University of Colorado, Boulder, 2005

Composite, continued

Participants

Component declares the shared interface declares child management operations empty methods for leaves defines an interface to retrieve parent Leaf implements shared interface Composite stores children implements shared interface by delegating to children implements child management operations Client Manipulates objects using the Component interface

Composite’s Structure and Roles

32 Component Operation() Add(Component) Remove(Component) GetChild(int) Leaf Operation() Composite Operation() Add(Component) Remove(Component) GetChild(int) children for all g in children g->Operation() Client

March 8, 2005 © University of Colorado, Boulder, 2005

Composite, continued

Collaborations

Client uses the Component interface to interact with all objects If the recipient is a leaf, then the request is handled directly If the recipient is a composite, then the request is delegated to its children 34

Composite, continued

Consequences

Composite allows primitive objects and composite objects to be treated transparently especially since the child management functions are defined in the Component interface Composite simplifies code in the client It makes it easy to add new types of “leaves” nothing needs to change to add a new type of component (not even the client) Disadvantage: Difficult to create composites that have only certain types of leaves; you need to subclass the Composite class and use run-time checks to make sure that only “legal” children are added to it