6/26/20151. copyright w. howden2 bridge, chain of responsibility, mediator, visitor, memento,...

57
03/15/22 1

Post on 21-Dec-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

04/18/23 1

Copyright W. Howden 2

Bridge, Chain of Responsibility, Mediator, Visitor, Memento, Strategy

CSE 111

04/18/23

Bridge Pattern Context and Problem

• Context

– An abstract class A is subclassed with alternative implementations that define its abstract methods. (Call this generalization hierarchy H1)

• Problem

– want to be able to vary the “front end” A without changing its implementations

Copyright W. Howden 304/18/23

Bridge Pattern Solution

• New Implementation Hierarchy– abstract class I with abstract methods that are

defined in subclasses that correspond to the implementation variations

• Front End Hierarchy– define a new class A which uses I and defines

the desired front end variations

04/18/23 Copyright W. Howden 4

Old Class Diagram

04/18/23 Copyright W. Howden 5

Comments

• The original class FrontEnd has methods which are implemented using certain features that can have alternatives

• Those different alternatives are modeled using subclasses that contain the different alternatives

04/18/23 Copyright W. Howden 6

New Class Diagram

04/18/23 Copyright W. Howden 7

Comments

• The new FrontEnd class is abstract because it has an abstract class variable implementation, whose subtypes values correspond to differing implementations

• As far as the implementation differences are concerned, they are taken care of by the implementation subtype, so the methods in FrontEnd do not have to be abstract

• The subtypes of FrontEnd now correspond to front end differences, corresponding to additional methods. The new front ends may extend some or all of the supertype front end methods

04/18/23 Copyright W. Howden 8

Sally, Pierre and Aiko

• Sally has a new career with a TV cooking show, where you see her whipping up her favorite dishes

• The show will done in different venues, with available cooking techniques. e.g. openFire, solar, electric, gas.

• So Sally has to be able to know how to “switch gears” and cook in several different ways

Copyright W. Howden 904/18/23

Foreign Interfaces

• When Sally goes to different countries it is better for a local host to be used

• Sally’s way of cooking, with the different techniques, is still valid, but the “presentation” has to vary

• So in France, Pierre will the cook and Japan it will be Aiko

04/18/23 Copyright W. Howden 10

Foreign Interfaces, cont

• Pierre and Aiko will employ all of Sally’s capabilities, which will include techniques for each of the different possible ways of cooking

• They may also add other local flair capabilities or alter something that Sally used to do

04/18/23 Copyright W. Howden 11

Sally, Pierre and Aiko Comments

• Sally originally has alternative subclasses for each of the cooking methods

• A new version of Sally uses different cooking techniques by calling on methods in an instance of a cooking techniques subclass, whose subtype variations correspond to different techniques

– the instance is passed in via the Sally constructor

• Pierre and Aiko subclass Sally which allows them all her cooking capabilities, to which they can make local flavor additions and alterations

– When they are created with an instance of the cooking techniques subclass, they inherit common methods from Sally

04/18/23 Copyright W. Howden 12

DS Example Original

• Version 1: Suppose we had designed our DS so that we had an abstract GUI with abstract methods for calls on the DL. For a particular implementation of the DL, we subclass the GUI to get a concrete GUI where the abstract methods are replaced by concrete method calls on the chosen implementation methods of the DL

• Allows us to vary the implementations of the requests made via the GUI

Copyright W. Howden 1304/18/23

DS Example with Bridge

• DL variations – Abstract DL interface with abstract methods. Subclassed with a

concrete DL’s, for different implementations of DL actions.

• GUI calls methods in the abstract DL. When an instance of GUI is created, an instance of a concrete DL subclass is handed– GUI can be subclassed with variations that have the same DL

interface, but present different GUI behavior

Copyright W. Howden 1404/18/23

Real Uses of Bridge

• Graphics objects such as in Window have a WindowPeer component that is constructed to work for a particular graphics platform

• Instead of subclassing the user interface classes with peer classes, instances of the user interface (sub) classes are instantiated with an instance of a particular peer subclass

Copyright W. Howden 1504/18/23

Chain of Responsibility, Mediator

• Chain of Responsibility– context: tasks to be done, multiple agents

– problem: how to parcel out

– solution: linear ordering of agents, each does it or passes it on to the next (what if no one?)

• Mediator– context: multiple agents who need to interact

– problem: hard to keep track of who knows what

– solution: central mediator who handles all communications, and knows agents’ current status

Copyright W. Howden 1604/18/23

Pamela/Fred/Jane/Sally/Henry– Chain of Responsibility

• Start up a personal services corp. They all receive broadcast email with requests– start shouting at each other across the room to

see who is going to do it

• Chain of responsibility solution– Request comes to Pamela who does or hands it

to Fred. Fred does it or hands it to Jane .... Each may do part of the task or all of it.

Copyright W. Howden 1704/18/23

Pamela/Fred/Jane/Sally/Henry– Mediator

• They appoint Henry as the office manager– Henry knows their schedules and capabilities

• Requests come into Henry, who looks at schedules and asks relevant, ideal agents if they can take care of all or part of the task– Mediator reminiscent of the Controller pattern,

with use of system controller

Copyright W. Howden 1804/18/23

Visitor Pattern

• Context– a collection of objects, each of which contains information

in possibly different forms, from which we want to collect various kinds of information

• Problem– for each new kind of information we have to open up the

objects and add new data gathering methods

– we do not want the report maker to have a giant switch with (# of kinds of objects) x (# of kinds of reports) branches

Copyright W. Howden 1904/18/23

Solution

• Two abstract hierarchies

– Report interface

• a subclass for each kind of report that we want to produce

• these are data gathering objects

– Information object interface

• a subclass for each kind of information object from which we will gather information

• Report subclasses

• each report subclass has a visit() method for each information object subclass

• instances of report subclasses are called “visitors”

Copyright W. Howden 2004/18/23

Solution (cont’)

• Information subclasses• each information subclass has an accept() method

that takes a report subclass object x (the “visitor”) that collects the info

• Traverser• for any kind of desired report, create a

visitor/instance x, and traverse the information subclass objects. For each information object y, perform y.accept(x). This will cause x.visit(this) to be called

Copyright W. Howden 2104/18/23

Report Class Structure

Copyright W. Howden 2204/18/23

Information Class Structure

Copyright W. Howden 2304/18/23

Solution (cont’)

• Overloaded visit() methods in Report subclasses?– every subclass has a set of methods all called

visit(), all with different definitions– Disambiguation

• how do you know which visit() method it is when you perform x.visit()?

– use class and parameter disambiguation

Copyright W. Howden 2404/18/23

Disambiguation

• Class Disambiguation– if we see x.visit(), we look in the class of x to

find definitions for this visit() method

• Parameter Disambiguation– if we see x.visit(y), we look in the visit()

methods for class x to find the one which has a parameter of the type of y

04/18/23 Copyright W. Howden 25

Observations

• To add new report types• add a new reports subclass with new information

gathering visit() methods for each kind of information object

• To add new information objects• add a new information subclass

• add a new reporting visit() method for the new kind of information to each report subtype

Copyright W. Howden 2604/18/23

Pamela, Fred, Jane, Sally Henry and the Commune

• They form a commune where they pool their resources

• Once a year they collect certain kinds of information– total money assets– total money debts

Copyright W. Howden 2704/18/23

Commune and Personality Types

• Fred is suspicious of corporate America, Sally is lax, and Jane and Henry are prudent– Fred keeps his money under his mattress and

only borrows privately with IOU’s– Sally just keeps her money in her purse and

sponges off her parents– Jane and Henry keep their money in a Canadian

Bank and have no debts

Copyright W. Howden 2804/18/23

Report Subclasses

• TotalAssets subclass– methods: visit(x Suspicious), visit(x Lax) visit(x Prudent)

– e.g. a Suspicious person passed a TotalAssets object will call its visit(this) method, which will add the money under the person’s mattress to the total assets

• TotalDebts subclass– methods: visit(x Suspicious), visit(x Lax) visit(x Prudent)

– e.g. a Suspicious person passed a TotalDebts object will call its visit(this) method, which will add in the IOUs to the total debt

Copyright W. Howden 2904/18/23

Information Subclasses

• Suspicious people– accept() method will call the visit(this) in the visitor,

where “this” will be of type Suspicious

• Lax people– accept() method will call the visit(this) method in the

visitor, where “this” will be of type Lax

• Prudent people– accept() method will call the visit(this) method in the

visitor, where “visit” will be of type Prudent

Copyright W. Howden 3004/18/23

Commune Report Generation

• To generate total money assets report– We get Henry to carry an instance, or visitor, of

TotalAssets to Fred, Jane and Sally. When they accept the visitor, they execute its visit(this) method. Fred will hence automatically execute the Suspicious version of visit, Sally the Lax one, and Jane the Prudent

Copyright W. Howden 3104/18/23

Commune Report Methods

• Since the report is of type TotalAssets, the suspicious version will count money under the mattress for the accepting information object

• The lax version will count money in information object’s purse

• The prudent version will count the money in the persons Canadian bank account

Copyright W. Howden 3204/18/23

Commune Final Report

• Henry then returns the TotalAssets report, which in this case has been designed to keep the totaled the amounts inside itself.

• To get a debt summary, Henry would carry around an instance of TotalDebts, and a similar process would occur.

Copyright W. Howden 3304/18/23

DS Example

• Dating system returns a free dinner voucher for each date

• The contracted restaurants submit a visit summary for each pair of visiting daters

• We have a data base of summaries• Restaurants may submit differently formatted

summaries, or even summaries with different information

Copyright W. Howden 3404/18/23

DS Example

• We want to create different reports from the collection of summaries

• Create a report interface, with subclasses for each kind of report

• Each instance of a report subclass has an information gathering visit() method for each kind of restaurant summary

• For a collection of summaries, we visit each one. The accept method of a summary will execute the visit() method in the visitor

Copyright W. Howden 3504/18/23

Other Alternatives to Commune Visitor Solution?

• Assume the information we want is total assets– Functional

– information objects have an x.assets() method

– iterate over the information object collection, applying a totaling program t(partialSum, x) to each object x

– Object animation– iterate over the information object collection, for each

information object x perform x.addIn(partialSum), where x.addIn adds in its assets amount to partial Sum

04/18/23 Copyright W. Howden 36

Copyright W. Howden 37

Functional Approach

• t() has a big switch statement with an entry for each of the different versions of information objects, because info differently formatted

• Different programs for different kinds of reports• To add a new type of report, create a new program• To add a new type of information object, add to

the switch statements of each of the different reporting functions (ouch!)

04/18/23

Copyright W. Howden 38

Object Animation

• A program would iterate over the information objects, executing their .addIn() method

• To add a new report type– have to change the code in the information subclasses

for each new kind of report (addIn may not be adequate for new kind of gathered information)

– (ouch!)

• To add a new kind of information object– new subclass of information objects

04/18/23

Assessment

• For functional approach, adding a new type of information object is a mess

• For object-animation approach, adding a new kind of report may be a mess– also strongly couples information objects with

report types

• Visitor Pattern avoids these pitfalls

04/18/23 Copyright W. Howden 39

Memento Pattern

• Context• saving and restoring the state of an object

• Problem• do not want to expose the objects innards to the

outside world

• Solution• object has a getState() and restoreState() which uses

objects of class Memento. Done in a way so that client does not have access to contents.

04/18/23 Copyright W. Howden 40

Copyright W. Howden 41

Interfaces and Classes

• Strategy: • object that might need to be rolled back supports a Rollbackee

interface– has the getState() and restoreState() method

• object that recognizes that a rollbackee object may need to be rolled back is a Rollbacker subclass

– gets the data structure used to save Rollbackee objects

• a Rollbacker sends a getState message to a Rollbackee object, which returns a Memento object that is saved by the Rollbacker

• Rollbacker sends a setState message to rollbackee with a Memento from which state can be restored

04/18/23

Copyright W. Howden 4204/18/23

Fred, Sally and Memento

• Sally is a CSE student with 2 difficult exams on one day. She can cram the day before, but when she takes exam 1 she will forget the material for exam 2

• She gets Fred (who is on holiday from manufacturing souvenirs) to help her, using the Memento pattern

04/18/23 Copyright W. Howden 43

Using the Mementos

• When Sally finishes studying for Exam 2, Fred sends her a getState() message, and saves the returned memento

• After Sally finishes exam 1, Fred sends a restoreState(m) message with the saved memento m. Sally’s method restores her state and she is ready for Exam 2.

04/18/23 Copyright W. Howden 44

DS Memento Example 1

• Recall that DL creates a DateRequest object in response to a request for a date

• Suppose that• users can repeatedly ask for dates

• A single DR object is created for a session which keeps a history of responses

• Implement an undo facility wherein DL saves a state memento for each use of a DR

04/18/23 Copyright W. Howden 45

DS Memento Example 2

• DateRequest is the Rollbackee

• dL, the Domain Logic subsystems interface is the Rollbacker

• Could extend rollbacking to all messages, not just getDate

04/18/23 Copyright W. Howden 46

Memento vs Command 1

• Memento: needs to get state and restore it by direct access with object where state exists. Suppose you want to save state just before doing an AddMember request– Would dL need to save the whole DataBase?

• Command: command knows what part of state it should save. Can selectively use methods of target object to restore

04/18/23 Copyright W. Howden 47

Memento vs Command 2

• If we use the Command Pattern, the dL will receive different kinds of command objects which it will execute

• The command object can save, inside itself, necessary information for an undo

• dL will stack commands• e.g. for AddMember, all it needs to remember is

who was added, so if undo’s back us up to this command its undo() will be straightforward.

04/18/23 Copyright W. Howden 48

Memento Useful?

• When is it better than a Command stack?– Not directly linked to state changing

requests/commands, so can respond to a state change request at any time

• user demanded checkpointing

• periodic checkpointing

04/18/23 Copyright W. Howden 49

Strategy Pattern

• Context• alternative algorithms, procedures for a task

• Problem• allow best choice of algorithms at run/initialization

• Solution• different algorithms are instances of subclasses of

the same class A. Program constructor has a parameter of type A used to pass the algorithm instance

04/18/23 Copyright W. Howden 50

Copyright W. Howden 51

Alternative Approaches?

• Functional: big switch that chooses an algorithm• No, new choices will require recoding

• Factory pattern: instantiate abstract create() with concrete create for chosen algorithm• No, this is subclassing at program creation time

04/18/23

Copyright W. Howden 52

Class Relationships

Application «interface»Algorithm

Algorithm1

Client

Algorithm2

Uses

04/18/23

Sally, Jane and Fred

• Fred, Sally, Jane, and Pamela have been quite successful in the their Souvenirs business and start to have fancy parties. The parties are pretty much the same and include a late night supper. They hire a chef named Henri to do the supper

• The each have a favorite recipe, so for a given party, an instance of Henry is created with the choice for the occasion

04/18/23 Copyright W. Howden 53

DS Example

• We have different date matching algorithms, which we like to experiment with. We model them as concrete subclasses of an abstract DateRequest class

• At start up time, we create an instance of a subclass which is passed as a parameter into Start, and then into the constructor for DL who sets its dR class variable to the object.

04/18/23 Copyright W. Howden 54

Copyright W. Howden 55

Java Strategy Example

• Programmers can choose between different layout managers for a frame

• E.g. for the Message Dialog object, we usedbuttonPanel.setLayout(new FlowLayout());

• Other possible layout managers:– Border, Grid, Card, etc.

04/18/23

The Patterns Gang

• Bridge: International Cooking Show

• Alternative fronts and real cook implementers

• Chain: Personal Services Corp

• Pamela to Fred, Fred to Jane, ....

• Mediator: Personal Services Corp

• Office mediator Henry, also the controller

• Visitor: Inventory at the Commune, different kinds

• Memento: Fred resets Sally’s brain for the exam

• Strategy: Fancy party: giving the supper Menu to Henri

04/18/23 Copyright W. Howden 56

Assignment

• Consider how the patterns in this lecture might be used in your project. Either adopt them or discuss how they could be used and what the pros and cons of those potential uses are.

04/18/23 Copyright W. Howden 57