Design Patterns Reid Holmes

Similar documents
Design Patterns Reid Holmes

Design Patterns B. Reid Holmes. Material and some slide content from: - Head First Design Patterns Book - GoF Design Patterns Book

Material and some slide content from: - GoF Design Patterns Book. Design Patterns #1. Reid Holmes. Lecture 11 - Tuesday October

THOMAS LATOZA SWE 621 FALL 2018 DESIGN PATTERNS

Design Patterns #3. Reid Holmes. Material and some slide content from: - GoF Design Patterns Book - Head First Design Patterns

Design Patterns. Comp2110 Software Design. Department of Computer Science Australian National University. Second Semester

The Strategy Pattern Design Principle: Design Principle: Design Principle:

SDC Design patterns GoF

Lecture 14: Design Patterns

Think of drawing/diagramming editors. ECE450 Software Engineering II. The problem. The Composite pattern

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011

Object-Oriented Oriented Programming

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar

Topics in Object-Oriented Design Patterns

Introduction to Software Engineering: Object Design I Reuse & Patterns

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

Design of Software Systems (Ontwerp van SoftwareSystemen) Design Patterns Reference. Roel Wuyts

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

Design for change. You should avoid

EPL 603 TOPICS IN SOFTWARE ENGINEERING. Lab 6: Design Patterns

DESIGN PATTERNS. Dominik Škoda CHARLES UNIVERSITY Faculty of Mathematics and Physics

Design Patterns V Structural Design Patterns, 2

Last Lecture. Lecture 17: Design Patterns (part 2) Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 4448/ Spring Semester, 2005

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

Design Pattern. CMPSC 487 Lecture 10 Topics: Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, et al.)

Design Patterns IV Structural Design Patterns, 1

An Introduction to Patterns

Design Patterns IV. Alexei Khorev. 1 Structural Patterns. Structural Patterns. 2 Adapter Design Patterns IV. Alexei Khorev. Structural Patterns

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently.

Last Lecture. Lecture 26: Design Patterns (part 2) State. Goals of Lecture. Design Patterns

Goals of Lecture. Lecture 27: OO Design Patterns. Pattern Resources. Design Patterns. Cover OO Design Patterns. Pattern Languages of Programming

Design Patterns (Part 2) CSCE Lecture 18-10/25/2016 (Partially adapted from Head First Design Patterns by Freeman, Bates, Sierra, and Robson)

Software Design Patterns. Background 1. Background 2. Jonathan I. Maletic, Ph.D.

Design Pattern What is a Design Pattern? Design Pattern Elements. Almas Ansari Page 1

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1

COSC 3351 Software Design. Design Patterns Behavioral Patterns (II)

Facade and Adapter. Comp-303 : Programming Techniques Lecture 19. Alexandre Denault Computer Science McGill University Winter 2004

Lecture 20: Design Patterns II

The Visitor Pattern. Design Patterns In Java Bob Tarr

Composite Pattern. IV.4 Structural Pattern

SOFTWARE PATTERNS. Joseph Bonello

Interface. Design Patterns 2. Why use Interface? Design Principles. Adapter 11/7/2011. Michael Li

Applying the Decorator Design Pattern

Object-Oriented Oriented Programming Command Pattern. CSIE Department, NTUT Woei-Kae Chen

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011

Design Patterns. An introduction

Design Patterns in C++

Design Patterns and Frameworks Command

Slide 1. Design Patterns. Prof. Mirco Tribastone, Ph.D

Design Patterns. Dr. Rania Khairy. Software Engineering and Development Tool

Software Eningeering. Lecture 9 Design Patterns 2

Design Patterns Lecture 2

Tuesday, October 4. Announcements

COSC 3351 Software Design. Design Patterns Behavioral Patterns (I)

Trusted Components. Reuse, Contracts and Patterns. Prof. Dr. Bertrand Meyer Dr. Karine Arnout

Design patterns. Jef De Smedt Beta VZW

COSC 3351 Software Design. Design Patterns Structural Patterns (I)

Plan. Design principles: laughing in the face of change. What kind of change? What are we trying to achieve?

2.1 Design Patterns and Architecture (continued)

Design Patterns. Decorator. Oliver Haase

Using Design Patterns in Java Application Development

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar

Idioms and Design Patterns. Martin Skogevall IDE, Mälardalen University

Implementing GUI context-sensitive help... ECE450 Software Engineering II. Implementing GUI context-sensitive help... Context-sensitive help

OODP Session 4. Web Page: Visiting Hours: Tuesday 17:00 to 19:00

administrivia today UML start design patterns Tuesday, September 28, 2010

Object-Oriented Oriented Programming

Design Pattern: Composite

2.1 Design Patterns and Architecture (continued)

The GoF Design Patterns Reference

Design Patterns. GoF design patterns catalog

Design Patterns. (and anti-patterns)

Keywords: Abstract Factory, Singleton, Factory Method, Prototype, Builder, Composite, Flyweight, Decorator.

Design PatternsReview. CSE 110 Discussion - Week10

DESIGN PATTERN - INTERVIEW QUESTIONS

Design Patterns. it s about the Observer pattern, the Command pattern, MVC, and some GUI. some more

Decorator Pattern. Steven R. Bagley

Laboratorio di Sistemi Software Design Patterns 2

Tecniche di Progettazione: Design Patterns

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP

Dr. Xiaolin Hu. Review of last class

I, J. Key-value observing (KVO), Label component, 32 text property, 39

Software Engineering Prof. Rushikesh K.Joshi IIT Bombay Lecture-15 Design Patterns

A Reconnaissance on Design Patterns

Design Patterns. Comp2110 Software Design. Department of Computer Science Australian National University. Second Semester

Appendix-A. A.1 Catalogues of Design Patterns. Below is the definition for each design pattern using the FINDER notation, followed

Applying the Observer Design Pattern

Pro Objective-C Design Patterns for ios

The Design Patterns Matrix From Analysis to Implementation

Tecniche di Progettazione: Design Patterns

Adapter pattern. Acknowledgement: Freeman & Freeman

Design Patterns: Structural and Behavioural

Software Design COSC 4353/6353 D R. R A J S I N G H

TDDB84: Lecture 6. Adapter, Bridge, Observer, Chain of Responsibility, Memento, Command. fredag 4 oktober 13

CSCI Object Oriented Design: Frameworks and Design Patterns George Blankenship. Frameworks and Design George Blankenship 1

CSC207H: Software Design Lecture 6

Design patterns. OOD Lecture 6

COSC 3351 Software Design. Design Patterns Structural Patterns (II) Edgar Gabriel. Spring Decorator

Object-oriented Software Design Patterns

Transcription:

Material and some slide content from: - Head First Design Patterns Book - GoF Design Patterns Book Design Patterns Reid Holmes

GoF design patterns $ %!!!! $ "! # &

Pattern vocabulary Shared vocabulary communicate qualities reduce verbosity focus on design increase understanding

Observer example Weather data example (similar to Eclipse example) WeatherData temp, humidity, pressure calls newdata() whenever something changes bad: update views directly from here WeatherViews Current View Forecast View Stats View

Composite Intent: Enable a group of objects to be treated as single object Motivation: Differentiating between interior and leaf nodes in tree-structured data data increases system complexity. Applicability: If you notice you are treating groups and individual of objects the same way Can also be used when primitives and objects need to be treated identically

Composite Participants: Component: base class Leaf: individual leaf node Composite: node that maintains a list of children nodes

Composite Implementation: 1) Composite maintains a list of child elements and methods to maintain the children. 2) Composite object applies overridden methods from the component across all child methods. Known uses: Related to: Decorators are often used along with the Composite pattern to augment objects while grouping them.

Facade Intent: Provide a unified, higher-level, interface to a whole module making it easier to use. Motivation: Composing classes into subsystems reduces complexity. Using a Facade minimizes the communication dependencies between subsystems. Applicability: When you want a simple interface to a complex subsystem. There are many dependencies between clients and a subsystem. You want to layer your subsystems.

Facade Participants: Facade Subsystem classes Collaborations: Clients interact subsystem via Facade. Consequences: Shields clients from subsystem components. Promotes weak coupling. (strong within subsystem, weak between them) Doesn t prevent access to subsystem classes.

Facade Implementation: 1) Analyze client / subsystem tangling. 2) Create interface. Abstract factories can also be used to add further decoupling. Known uses: Varied. Related to: Abstract Factory can be used with Facade to create subsystem objects. Facades are frequently Singletons. Abstracts functionality similar to Mediator but does not concentrate on communication.

Observer Intent: Define a one-to-many relationship between objects so that when an object changes state its dependents are updated automatically Motivation: To maintain consistency between multiple different objects without tightly coupling them Applicability: When you want to compartmentalize modifications to two dependent objects When you want to publish updates but not couple classes

Observer Structure: Participants: Subject: tracks observers and fires updates Observer: subscribes/unsubscribes to subjects, receives updates

Observer Collaborations Subjects call observer s update method when they change Subjects can forward data (push) or just send blank update notifications (pull) Consequences: Reduce coupling between subject & observer Support broadcast communication Can result in expensive updates

Observer Implementation: 1. Subjects track observers (abstract class helpful) 2.Caching updates 3. Push vs. pull Related to: Employed by MVC & MVP.

GWT example Window.addResizeHandler(new ResizeHandler() { @Override public void onresize(resizeevent event) { if (event.getwidth() > event.getheight()) { setportrait(false); } else { setportrait(true); } } });

Command Intent: Encapsulate requests enabling clients to log / undo them as required. Motivation: In situations where you need to be able to make requests to objects without knowing anything about the request itself or the receiver of the request, the command pattern enables you to pass requests as objects. Applicability: Parameterize requests. Specify, queue, and log actions. Support undo. Model high-level operations on primitive operations.

Command Structure Participants: Command / ConcreteCommand Client Invoker Receiver

Command Collaborations: Client creates ConcreteCommand and specifies receiver. Invoker stores ConcreteCommand object. Invoker requests execute on Command; stores state for undoing prior to execute (if undoable). Concrete invokes operations on its receiver to perform request. Consequences: Decouples the invoker from the object that knows how to perform an action. Commands are first-class objects. Commands can be assembled into composite. Adding new commands is easy.

Command Implementation: 1) How smart should a command be? 2) Support undo/redo. 3) Avoiding error accumulation in the undo process. Related to: Composite commands can be created; the Memento pattern can store undo state. Commands often use Prototype when they need to be stored for undo/redo.

State Intent: Allow an object to alter its behaviour when its internal state changes; the object will appear to change its class. Motivation: Systems often have a limited set of discrete states and will behave differently depending on its current state. The state pattern enables control of state-dependent operations. Applicability: Systems where runtime behaviour is dependent on the state of the system. When decisions are based on many flags that are in effect checking state before deciding which operation to perform.

State Participants: Context: maintain State reference; delegates behaviour through composition to State class. IState: define abstract operations ConcreteState: implement IState, update Context as required. Consequences: Localizes state-specific behaviour. Makes state-transitions explicit.

State REID HOLMES - SE2: SOFTWARE DESIGN & ARCHITECTURE

State Implementation: 1) Context maintains a reference to a State. 2) Concrete states implement state and have a reference to the context. On state-transition operations, the current state object can update the State reference in the context. Related to: Flyweight objects are often used for sharing State objects. Strategy looks structurally similar, although strategies do not change their context method, nor are they typically used as dynamically as States.

Strategy Intent: Define a family of algorithms that can be easily interchanged with each other Motivation: Support the open/closed principle by abstracting algorithms behind an interface; clients use the interface while subclasses provide the functionality and can be easily interchanged. Applicability: When you want to be able to replace a behaviour at runtime (strategy reference can be dynamically altered). When you want to have a family of behaviours that might not be applicable for the client class.

Strategy REID HOLMES - SE2: SOFTWARE DESIGN & ARCHITECTURE

Strategy Participants: Context contains reference to chosen strategy and invokes algorithm. Strategy interface declares algorithm structure. ConcreteStrategy implements algorithm. Context does not use any methods not defined in the Strategy interface. Consequences: Context uses the interface, not the concrete class. Concrete classes can be easily exchanged.

Strategy Implementation: 1) Create strategy interface and reference in client. 2) Interact only through interface. Related to: Abstract Factory uses inheritance to achieve a subset of what Strategy does though a composition-based behaviour. Decorators are similar but focus on extending the functionality of a base class.

Visitor Intent: Represent operations to be performed on classes of elements. Motivation: Consider a large tree of objects that you want to perform an analysis on; this could require changing many objects. Visitors enable these Applicability: When you have a large object structure you want to traverse. When you have many different operations you want to perform but don t want to pollute the objects. The objects rarely change but the operations may.

Visitor Structure Participants: Visitor / ConcreteVisitor Element / ConcreteElement ObjectStructure

Visitor Collaborations: Client creates the ConcreteVisitor that traverses the object structure. The visited object calls its corresponding visitor method on the ConcreteVisitor. Consequences: Adding new operations is easy. Visitor gathers related operations (and separates unrelated ones). Adding ConcreteElement classes is hard. Accumulating state. Negative: Breaking encapsulation. (visitor may need access to internal state)

Visitor Implementation: 1) Double dispatch. 2) Who traverses structure? Related to: Good at visiting Composite structures.

Decorator Intent: Dynamically add additional responsibilities to structures. Motivation: Sometimes we want to add new responsibilities to individual objects, not the whole class. Can enclose existing objects with another object. Applicability: Add responsibilities dynamically and transparently. Remove responsibilities dynamically. When subclassing is impractical.

Decorator Structure Participants: Component / concrete component Decorator / concrete decorator

Decorator (code ex) // the Window interface interface Window { // adds vertical scrollbar functionality public void draw(); // draws the Window class VerticalScrollBarDecorator extends WindowDecorator { public String getdescription(); public VerticalScrollBarDecorator (Window decoratedwindow) { } super(decoratedwindow); } // implementation of a simple Window public void draw() { class SimpleWindow implements Window { drawverticalscrollbar(); public void draw() { super.draw(); // draw window } } private void drawverticalscrollbar() {.. } public String getdescription() { public String getdescription() { return decoratedwindow.getdescription() +" and vert sb"; return "simple window"; } } } } // adds horizontal scrollbar functionality // abstract decorator class class HorizontalScrollBarDecorator extends WindowDecorator { abstract class WindowDecorator implements Window { public HorizontalScrollBarDecorator (Window decoratedwindow) { protected Window decoratedwindow; super(decoratedwindow); } public WindowDecorator (Window decoratedwindow) { public void draw() { this.decoratedwindow = decoratedwindow; drawhorizontalscrollbar(); } super.draw(); public void draw() { } decoratedwindow.draw(); private void drawhorizontalscrollbar() {.. } } public String getdescription() { } return decoratedwindow.getdescription() + "and horiz sb"; } public class DecoratedWindowTest { } public static void main(string[] args) { Window decoratedwindow = new HorizontalScrollBarDecorator ( new VerticalScrollBarDecorator(new SimpleWindow())); // print the Window's description System.out.println(decoratedWindow.getDescription());}}

Decorator Collaborations Decorators forward requests to component object. Consequences: More flexible. (than static inheritance; arbitrary nesting possible) Avoids feature-laden classes. (KISS and add functionality as needed.) Warn: Decorator & component are not identical. (equality can be thrown off because decorator!= decorated) Negative: Many of little objects. (Lots of small, similar-looking classes differentiated by how they are connected. hard to understand and debug.)

Decorator Implementation: 1) Interface conformance. (decorator interface required) 2) Abstract decorator not needed if only one decoration is required. 2) Keep component classes lightweight. (too heavyweight can overwhelm decorators 3) Changing a skin instead of changing the guts. (if component is heavy, consider strategy instead) Related to: Decorators are a kind of single-node Composite. Decorators can change the skin, Strategy pattern can change the guts.

Decorator Example Starbucks example Beverages: house, dark, decaf, espresso Toppings: whip, milk, soy, mocha,... Show Crazy class diagram (state explosion) -> sucky to update KEY: classes open for extension but closed for modification KEY: decorators mirror type of their decorating obj BAD: lots of little objects floating around

Proxy Intent: Provide a placeholder to control access to another object. Motivation: One reason to control access is cost: consider an object that is expensive to populate entirely but cheap to partially populate. (e.g., remote object, large file from disk, etc.) Applicability: (When a more versatile reference is needed.) Remote: Hide the fact that an object is remote. Virtual: Create expensive objects on demand. Protection: Protect access to objects. Smart reference: Performs additional actions.

Proxy Structure Participants: Proxy Subject / RealSubject

Proxy Collaborations: Client interacts with proxy. Proxy forwards req. to RealSubject as required. Consequences: Remote: location hidden. Virtual: Optimizations can be applied. Protection: Housekeeping / auth can occur.

Proxy Implementation: 1) Create common interface for Proxy/ RealSubject. 2) Reference Proxy in Client. 3) Proxy forwards requests as necessary. Known uses: Image manipulation / RPC. Related to: Similar to Adapter and Decorator. Decorators add responsibilities while proxies serve as mediators.