Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are...

47
Software Eningeering Lecture 9 – Design Patterns 2

Transcript of Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are...

Page 1: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Software Eningeering Lecture 9 – Design Patterns 2

Page 2: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Patterns covered

• Creational – Abstract Factory, Builder, Factory Method, Prototype, Singleton

• Structural – Adapter, Bridge, Composite,

Decorator, Facade, Flyweight, Proxy • Behavioral – Chain of Responsibility,

Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor 2

Page 3: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Structural Patterns

• How classes and objects are composed to form a larger structure

• Structural Class patterns – Uses inheritance to compose interfaces or

implementations • Structural Object patterns

– describes ways to compose objects to realize new functionality

• Adapter, Bridge, Composite, Decorator, Facade,

Flyweight, Proxy 3

Page 4: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Adapter – Problem/Applicability

• Interface mismatch

• Create a reusable class that cooperates with unrelated or unforeseen classes

4

Presenter
Presentation Notes
Imagine we have bought a new positioning system from a company. They have included the necessary code to get it working but their interface does not match ours…. What to do? Or getting to subsystems work together which wasn’t supposed to at design-time at a company or…
Page 5: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Adapter – Solution

5

Class Adapter

Adapter

Client Target + Request()

Adaptee + SpecificRequest()

+ Request()

SpecificRequest();

Page 6: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Adapter – Solution

6

Object Adapter

Client Target +Request()

Adaptee + SpecificRequest()

Adapter +Request()

(adaptee) adaptee->SpecificRequest();

Page 7: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

• What consequences do the differences have?

7

Page 8: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Adapter -- example

• Bought a new positioning system – Code included but interfaces mismatch

• Make an adapter to include the new

positioning system into our platform

8

Page 9: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Adapter – Example

9

public interface PullPositionDevice { public Coordinate getPosition(); }

Page 10: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Adapter – Example public interface PullPositionDevice { public Coordinate getPosition(); } ____________________________________________________________________________________________________________________

public class YPositionDevice extends YPosition implements PullPositionDevice {

public Coordinate getPosition() { String position = super.PositionRequest(); Coordinate c = //transform String to Coordinate return c; } } 10

Presenter
Presentation Notes
Could be useful if you actually need to use other parts of the third-party implementation and therefore need to have an Yposition device as well as a PullPosition Device.
Page 11: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Adapter – Example

11

public interface PullPositionDevice { public Coordinate getPosition(); } ____________________________________________________________________________________________________________________

public class YPositionDevice implements PullPositionDevice {

private YPosition yposition; public Coordinate getPosition() { String position = yposition.PositionRequest(); Coordinate c = // transform String to Coordinate

return c; } }

Presenter
Presentation Notes
Favour Composition over Inheritance, so if you don’t need to pass the object to old code (and therefore don’t need your object to be an Yposition device) then use Composition (ObjectAdapter)
Page 12: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Consequences

• Class adapter • Adapts Adoptee to Target by committing to a concrete

adapter class • Lets Adapter override some of Adaptee’s behavior • Can still act as the original Type if necessary

• Object Adapter • Lets a single Adapter work with many Adaptees • Makes it harder to override Adaptee behavior • Can not act as the original Type

12

Presenter
Presentation Notes
Med många adaptees: Tex om en adaptee tillhandahåller viss funktionalitet och en annan en annan del men man vill använda det som ett paket.
Page 13: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Bridge -- Problem

• Class with – some parts consisting of general code – some parts have several different

implementations

• Could use inheritance – put the general code in each subclass

• might not be flexible enough

13

Page 14: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Bridge – Solution

• Decouple the code – General code – Several different implementations

• The Bridge pattern decouples an

abstraction from its implementation so that the two can vary independently

14

Page 15: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Bridge -- UML

15

ConcreteImlementorA + OperationImp()

Imp->OperationImp()

+ Operation()

ConcreteImlementorB + OperationImp()

Abstraction Implementor + OperationImp()

RefinedAbstraction

Page 16: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Bridge – example

• Application to run on a desktop computer as well as a mobile phone – Screen size varies – Input capabilities vary

• Instead of making two different applications

we can make a bridge to the device specific implementations

16

Page 17: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Bridge example cont.

17

A1. public class Abstraction { A2. A3. public void close(){ A4. System.exit(0); A5. } A6. public void open() { A7. // do cool open stuff A8. } A9. public void undo() { A10. // undo stuff A11. } A12.

C1. public interface Implementor { C2. public void operationXImpl(); C3. } D1. public class ConcreteImplA D2. implements Implementor D3. { D4. public void operationXImpl() D5. { D6. // Do things D7. } D8. } E1. public class ConcreteImplB E2. implements Implementor E3. { E4. public void operationXImpl() E5. { E6. // Do other things E7. }}

A13. public void operationX() { A14. imp = getImp(); A15. imp->operationXImpl(); A16. } A17. }

Page 18: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Bridge -- usage

• Consequences – Decoupling interface and implementation

– Improved extensibility

– Hiding implementation details from clients

18

Page 19: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Composite -- Problem

• Structured design composed of several graphical objects

• Could implement in a single class – Larger designs will be hard to read – it will be less flexible

19

Page 20: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Composite – Solution

20

• Compose objects into a tree structure with composites and leaves

aComposite

aComposite aLeaf aLeaf aLeaf

aLeaf aLeaf aLeaf

for all children execute operation

Page 21: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Composite – Solution cont.

• In Java AWT there is a similar pattern for graphic objects. – java.awt.Container – java.awt.Component

21 Frame

Component

Container Button TextArea Label

Panel Window

Dialog

Page 22: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Composite -- UML

22

+ Operation() + Add(Component) + Remove(Component) + GetChild(int) : Component

Leaf + Operation()

Client Component

+ Operation() + Add(Component) + Remove(Component) + GetChild(int) : Component

Component children

forall g in children g.Operation();

Page 23: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Composite -- example

23

• Map application – map as background – A dot (your position) – A scale marker

• Scale marker could be a

composite in itself (line and text)

• When the map is redrawn it also lets all its children redraw

Page 24: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Composite – example cont.

24

A1. public abstract class MapObject { A2. protected boolean visible; A3. public void setVisible(boolean see) { A4. this.visible = see; A5. } A6. public abstract void paint(Graphics g); A7. } B1. public class MapCompass extends MapObject { B2. public void paint(Graphics g) { B3. if (g!=null) { B4. if(visible) { B5. // paint the compass B6. } } } } C1. public class MapPosition extends MapObject { C2. public void paint(Graphics g) { C3. if (g!=null) { C4. if(visible) { C5. // paint the dot showing the position C6. } } } }

Page 25: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Composite – example cont.2.

25

1. public class MapCanvas extends Canvas implements MapObject, Component 2. { 3. // ..... 4. // ..... 5. public void addMapObject(MapObject mo) { 6. children.addElement(mo); 7. } 8. 9. public void paint(Graphics g) { 10. // paint itself 11. for(int i=0; i<children.size(); i++) { 12. ((MapObject)children.elementAt(i)).paint(aGraphicsBuffer); 13. } 14. } 15. 16. // ..... 17. // ..... 18.}

Page 26: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Composite -- usage

• Consequences – Defines class hierarchies consisting of primitive

objects and composite objects

– Makes the client simple

– Makes it easier to add new kinds of components

26

Page 27: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

27

Let’s take a break! =)

Page 28: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Façade – Problem/Applicability

• You want to provide a uniform interface to a set of interfaces in a subsystem

• You want to make a subsystem easier to use

• There are many dependencies between clients and subsystems

28

Presenter
Presentation Notes
1)Define entry point 2) Default view which is good enough for most clients 3) Decouple with façade
Page 29: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Façade – Problem/Applicability

29

subsystem classes

Client1 Client2 Client3 Client4

Page 30: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Façade – Solution

30

Facade subsystem classes

Client1 Client2 Client3 Client4

Presenter
Presentation Notes
Structuring a system into subsystems helps reduce complexity. Subsystems are groups of classes, or groups of classes and other subsystems The interface exposed by the classes in a subsystem or set of subsystems can become quite complex One way to reduce this complexity is to introduce a facade object that provides a single, simplified interface to the more general facilities of a subsystem
Page 31: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Facade – Example

31

A1. public class Client1 { A2. FacadeClass1 c1; A3 FacadeClass2 c2; A4. ... A5. A6. public void operation() { A7. c1.operation1(); A8. c2.operation2(); A9. ... A10. } A11. }

B1. public class Client1 { B2. Facade facade; B3. B4. public void operation() { B5. facade.facadeOp1(); B6. facade.facadeOp2(); B7 ... B8. } ________________________ OR C1. public void operation() { C2. facade.facadeOp(); C3. } ________________________ C4. }

Presenter
Presentation Notes
One way communication!!!
Page 32: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Façade – Consequences

• Shields clients from subsystem components

• Promotes weak coupling between subsystem and client

• Doesn’t prevent use of subsystem classes if needed

32

Presenter
Presentation Notes
Benefits It hides the implementation of the subsystem from clients, making the subsystem easier to use It promotes weak coupling between the subsystem and its clients. This allows you to change the classes the comprise the subsystem without affecting the clients. It reduces compilation dependencies in large software systems It simplifies porting systems to other platforms, because it's less likely that building one subsystem requires building all others It does not prevent sophisticated clients form accessing the underlying classes Note that Facade does not add any functionality, it just simplifies interfaces Liabilities It does not prevent clients from accessing the underlying classes!
Page 33: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Summary - structural • Adapter

– Lets classes with incompatible interfaces work together

• Bridge – Decouple an abstraction from its implementation

so that the two can vary independently • Composite

– Lets clients treat individual objects and compositions of objects uniformly

• Facade – Provide a unified interface to a set of interfaces

in a subsystem 33

Page 34: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Behavioural patterns

• Concerned with algorithms and assignment of responsibilities. – Complex control-flow that’s hard to follow at

run-time – class: use inheritance to distribute behaviour

between classes – object: object composition to, for example,

describe how a group of objects should cooperate

34

Page 35: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Chain of Responsibility – Problem • You want to avoid coupling the sender of a

request with a certain receiver

• More than one object may handle a request and the handler isn’t known beforehand

• The set of objects that can handle a request should be specified dynamically

35

Presenter
Presentation Notes
The object that ultimately handles the request isn’t, and shouldn’t be, explicitly known to the sender
Page 36: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Chain of Responsibility – Solution

36

Handler +handleRequest() : void

ConcreteHandler1 +handleRequest(): void

ConcreteHandler2 +handleRequest(): void

successor

Client

Page 37: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Chain of Responsibility – Solution

37

HelpHandler +handleHelp() : void

Application +handleHelp(): void

handler

Client

Widget +handleHelp(): void

Dialog

if can handle { showHelp(); } else { Handler::handleHelp(); }

Button +handleHelp(): void -showHelp(): void

handler->handleHelp()

Page 38: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Chain of Responsibility – Consequences

• Reduced coupling

• Added flexibility in assigning responsibilities to objects

• Receipt isn’t guaranteed

38

Presenter
Presentation Notes
Implementation issues!!
Page 39: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Iterator

• Lists etc. – More than just an array, but how?

39

Page 40: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Iterator – Problem/Applicability

• You wish to create an aggregated object – Access the elements sequentially – Don’t want to expose underlying

representation

• Want to support multiple types of traversals • Remember state

40

Presenter
Presentation Notes
2) won’t have to bloat the aggregate class with traversal operations 3) Provide a uniform traversal interface for all traversals and aggregates
Page 41: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Iterator – Solution

41

ConcreteAggregate + createIterator()

Iterator + first() + next() + isDone() + currentItem()

ConcreteIterator + first() + next() + isDone() + currentItem()

Aggregate + createIterator()

return new ConcreteIterator(this)

Presenter
Presentation Notes
Client doesn’t have to care about if the lists/aggregates are hashtables, lists, arrays, trees or whatever...
Page 42: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

42

Iterator -- example

Page 43: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Iterator – Example

43

1. public class Client { 2. private Aggregate agg; 3. 4. public void setAggregate(Aggregate agg) { 5. this.agg = agg; 6. } 7. 8. public void print() { 9. Iterator iterator = this.agg.createIterator(); 10. while (!iterator.isDone()) { 11. System.out.println(iterator.currentItem()); 12. iterator.next(); 13.}}}

Page 44: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Iterator – 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

• Remembers its own state

44

Page 45: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Iterator – Implementation Issues • Who controls the iteration? • Who defines the traversal algorithm? • How robust is the iterator? • Additional Iterator operations

45

Presenter
Presentation Notes
External – client, external more flexible (e.g. Comparison between two collections) and client has to request next element and advance the traversal, Internal – iterator control, client sends the operation to be done to the iterator which applies it to the elements (easier to use, control logic defined by iterator) Iterator or aggregate? If aggregate-> store state in iterator, called cursor, with iterator easier can use different types of iterations on the same aggregate, but could violate encapsulation Add, delete during traversal possible? Robust if that is possible without copying the aggregate Previous?SkipTo? Good to use on for example trees when coming to a leaf. It is always done. Might also be easier to use internal iterator on trees.
Page 46: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Summary - behavioral

• Chain of Responsibility – Avoid coupling the sender of a request to its

receiver by giving more than one object a chance to handle the request.

• Iterator

– Provide a way to access the elements of an aggregate object sequentially

46

Page 47: Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are composed to form a larger structure • Structural Class patterns – Uses inheritance

Questions?

47