Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are...
Transcript of Lecture 9 – Design Patterns 2€¦ · Structural Patterns • How classes and objects are...
Software Eningeering Lecture 9 – Design Patterns 2
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
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
Adapter – Problem/Applicability
• Interface mismatch
• Create a reusable class that cooperates with unrelated or unforeseen classes
4
Adapter – Solution
5
Class Adapter
Adapter
Client Target + Request()
Adaptee + SpecificRequest()
+ Request()
SpecificRequest();
Adapter – Solution
6
Object Adapter
Client Target +Request()
Adaptee + SpecificRequest()
Adapter +Request()
(adaptee) adaptee->SpecificRequest();
• What consequences do the differences have?
7
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
Adapter – Example
9
public interface PullPositionDevice { public Coordinate getPosition(); }
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
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; } }
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
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
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
Bridge -- UML
15
ConcreteImlementorA + OperationImp()
Imp->OperationImp()
+ Operation()
ConcreteImlementorB + OperationImp()
Abstraction Implementor + OperationImp()
RefinedAbstraction
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
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. }
Bridge -- usage
• Consequences – Decoupling interface and implementation
– Improved extensibility
– Hiding implementation details from clients
18
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
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
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
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();
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
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. } } } }
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.}
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
27
Let’s take a break! =)
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
Façade – Problem/Applicability
29
subsystem classes
Client1 Client2 Client3 Client4
Façade – Solution
30
Facade subsystem classes
Client1 Client2 Client3 Client4
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. }
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
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
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
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
Chain of Responsibility – Solution
36
Handler +handleRequest() : void
ConcreteHandler1 +handleRequest(): void
ConcreteHandler2 +handleRequest(): void
successor
Client
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()
Chain of Responsibility – Consequences
• Reduced coupling
• Added flexibility in assigning responsibilities to objects
• Receipt isn’t guaranteed
38
Iterator
• Lists etc. – More than just an array, but how?
39
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
Iterator – Solution
41
ConcreteAggregate + createIterator()
Iterator + first() + next() + isDone() + currentItem()
ConcreteIterator + first() + next() + isDone() + currentItem()
Aggregate + createIterator()
return new ConcreteIterator(this)
42
Iterator -- example
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.}}}
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
Iterator – Implementation Issues • Who controls the iteration? • Who defines the traversal algorithm? • How robust is the iterator? • Additional Iterator operations
45
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
Questions?
47