1 / 41

Software Eningeering

Software Eningeering. Lecture 10 – Design Patterns 3. Patterns covered. Creational – Abstract Factory, Builder, Factory Method, Prototype, Singleton Structural – Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy

Download Presentation

Software Eningeering

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Software Eningeering Lecture 10 – Design Patterns 3

  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

  3. 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

  4. Observer – Problem/Applicability • Keep consistency between related objects • You might not know beforehand which classes are interested in the state change information

  5. observers Observer Subject +Update() +Attach(Observer) +Detach(Observer) +Notify() For all o in observers { o->Update() } subject ConcreteObserver ConcreteSubject -observerState -subjectState +Update() +GetState() +SetState() observerState = subject->GetState() return subjectState Observer – Solution

  6. 1. public interface PositionListener { 2. public void positionUpdate(); 3. } 4. 5. public abstract class PositionDevice { 6. private Vector listeners; 7. public void addPositionListener(PositionListener pl) { 8. listeners.add(pl); 9. } 10. public void removePositionListener(PositionListener pl) { 11. listeners.remove(pl); 12. } 13. 14. public void dispatchPosition() { PositionListener pl = null; Enumeration e = listeners.elements(); 17. while (e.hasMoreElements()) { 18. pl = (PositionListener)e.nextElement(); 19. pl.positionUpdate(); 20. } } } Observer – Example

  7. 1. public class PushPositionDevice extends PositionDevice { 2. private Coordinate currentCoord; 3. public void setPosition(Coordinate c) { 4. this.currentCoord = c; 5. dispatchPosition(); 6. } 7. 8. public Coordinate getPosition() { 9. return this.currentCoord; 10.} 11.} Observer – Example

  8. 1. public class PositionObserver implements PositionListener { 2. private PushPostionDevice subject; 3. 4. public PositionObserver() { 5. subject = new PushPositionDevice(); 6. subject.addPositionListener(this); 7. } 8. 9. public void positionUpdate() { 10. Coordinate c = subject.getPosition(); 11. // paint position on map 12. } 13.} Observer - Example

  9. Observer - Consequences • Abstract coupling between Subject and Observer • Support for broadcast communication • Unexpected updates

  10. Observer – Implementation Issues • Observing more than one subject • Who triggers the update? • Dangling references to deleted subjects • Notify at the right time • The update protocol

  11. State – Problem/Applicability • Imagine you have a system which behaves differently depending on which state it is in • Putting the different behaviour in if-else paragraphs might make your code hard to follow, it also makes it hard to change

  12. State-diagram

  13. Context State + Request() + Handle() state->Handle() ConcreteStateA ConcreteStateB + Handle() + Handle() State – Solution Put the different states in different classes and use a State-pattern to let your object alter its behaviour when its internal state changes.

  14. State – Example • Example (from the book) – TCP connection • If the connection is closed we can do an active open and a passive open • If a connection is established we can transmit info and close the connection • …

  15. Without State pattern: 1. public class TCPConnection { 2. private int state; 3. public TCPConnection() { 4. state =TCP_CLOSED; 5. } 6. 7. public void activeOpen() { 8. switch(this.state) { 9. case TCP_CLOSED: 10. // do whatever 11. case TCP_LISTENING: 12. //do something else 13. … 14. } }} State – Example • With State pattern: • B1. public class TCPConnection { • B2. private TCPState state; • B3. • B4. public TCPConnection() { • B5. state = new TCPClosed(); • B6. } • B7. • B8. public void activeOpen() { • B9 state.activeOpen(this); • B10. } • B11. • B12. public void passiveOpen() { • B13. state.passiveOpen(this); • B14. } • B15. }

  16. State – TCPState // Implements general behaviour for listed methods 1. abstract class TCPState { 2. public void activeOpen(TCPConnection tcp) {} 3. public void passiveOpen(TCPConnection tcp){} 4. public void acknowledge(TCPConnection tcp) {} 5. public void transmit(TCPConnection tcp) {} 6. public void close(TCPConnection tcp) {} 7. ... 8. } Implement with or without error handling

  17. State – Example 1. public class TCPClosed extends TCPState { 2. public void activeOpen(TCPConnection tcp) { 3. //do stuff 4. tcp.setState(new TCPEstablished()); 5. } 6. 7. public void passiveOpen(TCPConnection tcp) { 8. //do stuff 9. tcp.setState(new TCPListening()); 10. } 11. } B1. public class TCPListening extends TCPState { B2. public void acknowledge(TCPConnection tcp) { B3. //do stuff B4. tcp.setState(new TCPEstablished()); B5. } B6. }

  18. State – Consequences • It localizes state-specific behaviour and partitions behaviour for different states • It makes state transitions explicit

  19. State – Implementation Issues • Who defines state transitions? • Creating and destroying State objects

  20. Strategy – Problem/Applicability • When many related classes differ only in their behaviour • When you need different variants of an algorithm • When an algorithm uses data that clients shouldn’t know about • When a class defines many behaviours, and these appear as multiple conditional statements in its operations

  21. Strategy – Solution Put each algorithm in a separate class and use the Strategy pattern to change between algorithms strategy Context Strategy + AlgorithmInterface() + ContextInterface() ConcreteStrategyA ConcreteStrategyB + AlgorithmInterface() + AlgorithmInterface()

  22. Strategy -- example A1. // Abstract Strategy class A2. public abstract class SortStrategy { A3. public abstract void sort(); A4. } B1. // Context class B2. public class AddressBook { B3. //Default Algorithm B4. private SortStrategy strategy = new SortByName(); B5. B6. public void changeStrategy(SortStrategy newStrategy) { B7. this.strategy = newStrategy; B8. } B9. B10. public void sort() { B11. strategy.sort(); B12. } }

  23. Strategy – example cont. A1. public class SortByName extends SortStrategy{ // ConcreteStrategyA class A2. public void sort(){ A3. // implementation A4. } } B1. public class SortByAge extends SortStrategy{ // ConcreteStrategyB class B2. public void sort(){ B3. // implementation B4. } } C1. public class Test { C2. public static void main(String [] argv) { C3. AddressBook ab = createAddressBook(“filename”); C4. ab.sort(); C5. ab.showFirst(); C6. ab.changeStrategy(new SortByAge()); C7. ab.sort(); C8. ab.showFirst(); C9. }}

  24. Strategy – Consequences • Families of related algorithms • An alternative to subclassing • Strategies eliminate conditional statements • A choice of implementations • Clients must be aware of different Strategies • Communication overhead between Strategy and Context • Increased number of objects

  25. Let’s have a break =)

  26. Class1 Class4 Class2 Class3 Mediator – Problem/Applicability • Object-oriented programming encourages distribution of behaviour • Interconnections tend to reduce usability

  27. Mediator – Problem/Applicability • When a set of objects communicate in well-defined but complex ways • When reusing an object is difficult because it refers to and communicates with many other objects • When a behaviour that’s distributed between several classes should be customizable without a lot of subclassing

  28. Mediator – Solution mediator Mediator Colleague ConcreteMediator ConcreteColleague1 ConcreteColleague1 Class1 Class4 MediatorClass Class2 Class3

  29. 1. public class MyButton extends Button { 2. private Dialog dialog; 3. private Checkbox cb1, cb2; 4. 5. //called when button is pressed 6. public void press() { 7. boolean checked = this.cb1.checked(); 8. this.cb2.setChecked(checked); 9. this.dialog.update(); 10. } 11. …. 12. } Not using MediatorNote how the MyButton class needs to know about the Dialog and Checkbox, and how the MyCheckBox needs to know about RadioButton and Button… Complex communication B1. public class MyCheckBox B2. extends Checkbox { B3. private RadioButton rb; B4. private Button button; B5. B6. //called when box gets checked B7. public void checked() { B8. this.button.enable(); B9. } B10. …. B11. }

  30. 1. public class MyMediator { 2. private Dialog dialog; 3. private Checkbox cb1, cb2; 4. private Button button; 5. private RadioButton rb; 6. 7. public void pressedButton() { boolean checked = this.cb1.checked(); 9. this.cb2.setChecked(checked); 10. this.dialog.update(); 11. } 12. …. 13. } Mediator – ExampleHere we let the MyMediator class handle all the communication. This makes the MyButton class a lot easier to read B1. public class MyButton B2. extends Button { B3. private MyMediator mediator; B4. B5. public void press() { B6. this.mediator.pressedButton(); B7. } B8. …. B9. }

  31. Mediator – Consequences • It limits the need for subclassing to just the mediator • It decouples colleagues • It simplifies object protocols • It abstracts how objects cooperate • It centralizes control

  32. Command – Problem • You want to encapsulate a request as an object • You want to be able to issue requests without knowing anything about the operation being requested

  33. Invoker Command +execute() : void Client Receiver receiver +action(): void ConcreteCommand instantiates -state: State +execute(): void receiver->action(); Command – Solution

  34. JFrame <<ActionListener>> JMenuItem instantiate GUI MyMenuItem -initMenu() command Command ExitCommand OpenCommand Command – Example

  35. Command – Example A1. public interface Command { A2. public void execute(); A3. } 1. import javax.swing.JMenuItem; 2. public class MyMenuItem extends JMenuItem { 3. private Command command; 4. 5. public MyMenuItem(Command command, String label) { 6. super(label); 7. this.command = command; 8. } 9. 10. public void executeCommand() { 11. if (command != null) { 12. command.execute(); 13. }}}

  36. Command – Example 1. import java.awt.event.*; 2. import javax.swing.*; 3. public class GUI extends JFrame implements ActionListener { 4. 5. public GUI() { 6. super(); 7. initMenu(); 8. addWindowListener(new WindowAdapter() { 9. public void windowClosing() { 10. System.exit(0); 11. } 12. }); 13. pack(); 14. }

  37. Command – Example 1. private void initMenu() { 2. JMenuBar bar = new JMenuBar(); 3. JMenu menu = new JMenu("File"); 4. JMenuItem item = new MyMenuItem(new OpenCommand(), "Open"); 5. item.addActionListener(this); 6. menu.add(item); 7. item = new MyMenuItem(new ExitCommand(), "Exit"); 8. item.addActionListener(this); 9. menu.add(item); 10. bar.add(menu); 11. this.setJMenuBar(bar); 12. } 13. 14. public void actionPerformed(ActionEvent e) { 15. MyMenuItem item = (MyMenuItem) e.getSource(); 16. item.executeCommand(); 17. }}

  38. Command – Applicability • Use when you want to: • specify, queue, and execute requests at different times • support undo • support logging changes

  39. Command - Consequences • Decouples invoker from performer • Easy to add new commands

  40. Summary • Patterns • Creational • Structural • Behavioural

  41. Questions?

More Related