• Non ci sono risultati.

Design Patterns

N/A
N/A
Protected

Academic year: 2021

Condividi "Design Patterns"

Copied!
47
0
0

Testo completo

(1)

TITLE

Laboratorio di Progettazione di Sistemi Software

Design Patterns

Comportamentali

(2)

© 2002-2005 Riccardo Solmi 2

Indice degli argomenti

ƒ Catalogo di Design Patterns comportamentali:

• Template Method

• Visitor

• Iterator

• Strategy

• State

• Observer

• Command

(3)

Template Method

ƒ Intent

• Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses

redefine certain steps of an algorithm without changing the algorithm's structure

ƒ Applicability

• to implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.

(4)

© 2002-2005 Riccardo Solmi 4

Template Method /2

ƒ Structure

ConcreteClass

implements the primitive operations to carry out subclass-specific steps of the algorithm.

ƒ Participants

AbstractClass

defines abstract primitive

operations that concrete subclasses define to implement steps of an algorithm.

implements a template method defining the skeleton of an

algorithm. The template method calls primitive operations as well as operations defined in

AbstractClass or those of other objects.

(5)

Template Method /3

ƒ Collaborations

• ConcreteClass relies on AbstractClass to implement the invariant steps of the algorithm

ƒ Consequences

• Template methods lead to an inverted control structure that's sometimes referred to as "the Hollywood principle," that is,

"Don't call us, we'll call you"

• It's important for template methods to specify which

(6)

© 2002-2005 Riccardo Solmi 6

Template Method example 1

(7)

Template Method example 2

ƒ Application framework that provides Application and Document classes

(8)

© 2002-2005 Riccardo Solmi 8

Template Method questions

ƒ The Template Method relies on inheritance. Would it be

possible to get the same functionality of a Template Method, using object composition? What would some of the tradeoffs be?

(9)

Visitor

ƒ Intent

Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates

ƒ Applicability

an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes

many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes

(10)

© 2002-2005 Riccardo Solmi 10

Visitor /2

ƒ Structure

(11)

Visitor /3

ƒ Collaborations

• A client that uses the Visitor pattern must create a ConcreteVisitor object and then traverse the object structure, visiting each element with the visitor

• When an element is visited, it calls the Visitor operation that corresponds to its class. The element supplies itself as an

argument to this operation to let the visitor access its state, if necessary

(12)

© 2002-2005 Riccardo Solmi 12

Visitor /4

ƒ The following interaction diagram illustrates the collaborations between an object structure, a visitor, and two elements

(13)

Visitor /4

ƒ Consequences

• Visitor makes adding new operations easy

• A visitor gathers related operations and separates unrelated ones

• Adding new ConcreteElement classes is hard

• Visiting across class hierarchies

• Accumulating state

• Breaking encapsulation

(14)

© 2002-2005 Riccardo Solmi 14

Visitor example 1

(15)

Visitor example 2

ƒ Compiler that represents programs as abstract syntax trees

(16)

© 2002-2005 Riccardo Solmi 16

Visitor Questions

ƒ One issue with the Visitor pattern involces cyclicality. When you add a new Visitor, you must make changes to existing code. How would you work around this possible problem?

(17)

Iterator

ƒ Intent

• Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation

ƒ Applicability

• to access an aggregate object's contents without exposing its internal representation.

• to support multiple traversals of aggregate objects.

• to provide a uniform interface for traversing different

(18)

© 2002-2005 Riccardo Solmi 18

Iterator /2

ƒ Structure

ƒ Participants

Iterator

• defines an interface for accessing and traversing elements.

ConcreteIterator

• implements the Iterator interface.

• keeps track of the current position in the traversal of the aggregate.

Aggregate

• defines an interface for creating an Iterator object.

ConcreteAggregate

• implements the Iterator creation interface to return an instance of the proper ConcreteIterator.

(19)

Iterator /3

ƒ Collaborations

• A ConcreteIterator keeps track of the current object in the aggregate and can compute the succeeding object in the traversal

ƒ Consequences

• It supports variations in the traversal of an aggregate

• Iterators simplify the Aggregate interface

• More than one traversal can be pending on an aggregate

(20)

© 2002-2005 Riccardo Solmi 20

Iterator example 1

(21)

Iterator example 2

ƒ An aggregate object such as a list should give you a way to access its elements without exposing its internal structure

(22)

© 2002-2005 Riccardo Solmi 22

Iterator questions

ƒ Consider a composite that contains loan objects. The loan object interface contains a method called

"AmountOfLoan()", which returns the current market value of a loan. Given a requirement to extract all loans above,

below or in between a certain amount, would you write or use an Iterator to do this?

(23)

Strategy

ƒ Intent

• Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

ƒ Applicability

• Many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many

behaviors.

• You need different variants of an algorithm.

(24)

© 2002-2005 Riccardo Solmi 24

Strategy /2

ƒ Structure

ƒ Participants

Strategy

• declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.

ConcreteStrategy

• implements the algorithm using the Strategy interface

Context

• is configured with a ConcreteStrategy object.

• maintains a reference to a Strategy object.

• may define an interface that lets Strategy access its data

(25)

Strategy /3

ƒ Collaborations

Strategy and Context interact to implement the chosen algorithm. A context may pass data or itself to the Strategy.

A context forwards requests from its clients to its strategy.

Clients usually create and pass a ConcreteStrategy to the context;

thereafter, they interact with the context exclusively.

ƒ Consequences

Families of related algorithms.

An alternative to subclassing. Vary the algorithm independently of its context even dynamically.

Strategies eliminate conditional statements.

(26)

© 2002-2005 Riccardo Solmi 26

Strategy example 1

ƒ Sorting Strategy

(27)

Strategy example 2

ƒ To define different algorithms

(28)

© 2002-2005 Riccardo Solmi 28

Strategy questions

ƒ What happens when a system has an explosion of Strategy objects? Is there some way to better manage these strategies?

ƒ Is it possible that the data required by the strategy will not be available from the context's interface? How could you remedy this potential problem?

(29)

State

ƒ Intent

• Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

ƒ Applicability

• An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.

• Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several

(30)

© 2002-2005 Riccardo Solmi 30

State /2

ƒ Structure

ƒ Participants

• Context

– defines the interface of interest to clients.

– maintains an instance of a ConcreteState subclass that defines the current state.

• State

– defines an interface for encapsulating the behavior associated with a particular state of the Context.

• ConcreteState subclasses

– each subclass implements a behavior associated with a state of the Context.

(31)

State /3

ƒ 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 the ConcreteState subclasses can decide which state succeeds another and under what circumstances.

(32)

© 2002-2005 Riccardo Solmi 32

State /4

ƒ Consequences

• It localizes state-specific behavior and partitions behavior for different states.

• It makes state transitions explicit.

• State objects can be shared.

ƒ Implementation

• Who defines the state transitions?

• Creating and destroying State objects

• A table-based alternative

(33)

State example 1

ƒ Queue

(34)

© 2002-2005 Riccardo Solmi 34

State example 2

ƒ Network connection

(35)

State example 3

ƒ Drawing tool

(36)

© 2002-2005 Riccardo Solmi 36

State Questions

ƒ If something has only two to three states, is it overkill to use the State pattern?

(37)

Observer

ƒ Intent

• Define a one-to-many dependency between objects so that when one object changes state, all its dependents are

notified and updated automatically.

ƒ Applicability

• When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.

• When a change to one object requires changing others,

and you don't know how many objects need to be changed.

(38)

© 2002-2005 Riccardo Solmi 38

Observer/2

ƒ Structure

ƒ Structure

(39)

Observer/3

ƒ Participants

• Subject: knows its observers. Any number of Observer objects may observe a subject.◦provides an interface for attaching and detaching Observer objects.

• Observer: defines an updating interface for objects that should be notified of changes in a subject.

• ConcreteSubject: stores state of interest to

ConcreteObserver objects and sends a notification to its observers when its state changes.

• ConcreteObserver: maintains a reference to a

(40)

© 2002-2005 Riccardo Solmi 40

Observer/4

ƒ Collaborations

• ConcreteSubject notifies its observers whenever a change occurs that could make its observers' state inconsistent with its own.

• After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for

information. ConcreteObserver uses this information to reconcile its state with that of the subject.

(41)

Observer/5

ƒ The following interaction diagram illustrates the collaborations between a subject and two observers:

(42)

© 2002-2005 Riccardo Solmi 42

Observer/6

ƒ Consequences

• The Observer pattern lets you vary subjects and observers independently.

• You can reuse subjects without reusing their observers, and vice versa.

• It lets you add observers without modifying the subject or other observers.

• Abstract coupling between Subject and Observer.

• Support for broadcast communication.

• Unexpected updates.

(43)

Command

ƒ Intent

• Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

ƒ Applicability

• parameterize objects by an action to perform. Commands are an object-oriented replacement for callbacks.

• specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the

(44)

© 2002-2005 Riccardo Solmi 44

Command/2

ƒ Structure

ƒ Participants

Command:

• declares an interface for executing an operation

ConcreteCommand:

• defines a binding between a Receiver object and an action

• Implements Execute by invoking the

corresponding

operation on Receiver

Client:

• Creates a ConcreteCommand object and sets its receiver

Invoker:

• Asks the command to carry out the request

Receiver:

• Knows how to perform the operations associated with

carrying out a request. Any class may serve as a receiver

(45)

Command/3

ƒ Collaborations

• The client creates a ConcreteCommand object and specifies its receiver.

• An Invoker object stores the ConcreteCommand object.

• The invoker issues a request by calling Execute on the command. When commands are undoable,

ConcreteCommand stores state for undoing the command prior to invoking Execute.

• The ConcreteCommand object invokes operations on its receiver to carry out the request.

(46)

© 2002-2005 Riccardo Solmi 46

Command/4

ƒ Collaborations (continue)

ƒ The following diagram shows the interactions between these objects

(47)

Command/5

ƒ Consequences

• Command decouples the object that invokes the operation from the one that knows how to perform it.

• Commands are first-class objects. They can be manipulated and extended like any other object.

• You can assemble commands into a composite command. In general, composite commands are an instance of the

Composite pattern.

• It's easy to add new Commands, because you don't have to change existing classes.

Riferimenti

Documenti correlati

Our attention focusses mainly on the local housing patterns where the signs of the historical and 

Using the construction of Containing Spaces given in [1] we define some kind of games considered on topological classes of spaces.. Keywords: topological game, containing

of electrons condensated in the superconductive states n s are a fraction of the system, according to the second order phase transition theory.. If we compute the current, there is

• an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes. •

If a method of a base class specifies an exception list, all derived classes that override that method must specify the same exception list, else the compiler will complain. Java

public abstract class Wind extends Instrument { abstract public void play(Note n);. public String what() { return "Wind"; } public void

Each node may have a parent node A tree consists of one root node, plus zero or more children sub-trees..

Lipari (Scuola Superiore Sant’Anna) Introduction to Java October 29, 2010 1 /