Design Patterns. CSE870: Advanced Software Engineering (Design Patterns): Cheng

Similar documents
Design Patterns! Acknowledgements!

CSE870: Advanced Software Engineering (Cheng) 1

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

Design Patterns. An introduction

Design Patterns. Gunnar Gotshalks A4-1

SDC Design patterns GoF

Introduction to Patterns and Frameworks

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

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

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

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

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

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

A Reconnaissance on Design Patterns

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

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

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

Design Patterns. GoF design patterns catalog

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

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

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

Using Design Patterns in Java Application Development

Design Patterns. Observations. Electrical Engineering Patterns. Mechanical Engineering Patterns

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

Topics in Object-Oriented Design Patterns

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

Introduction and History

DESIGN PATTERN - INTERVIEW QUESTIONS

Object-Oriented Design

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

Object-oriented Software Design Patterns

Object-Oriented Oriented Programming

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

An Introduction to Patterns

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

INSTITUTE OF AERONAUTICAL ENGINEERING

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

Introduction to Software Engineering: Object Design I Reuse & Patterns

Coordination Patterns

Lecture 20: Design Patterns II

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

Creational Design Patterns

CSCI 253. Overview. The Elements of a Design Pattern. George Blankenship 1. Object Oriented Design: Iterator Pattern George Blankenship

Lectures 24 and 25 Introduction to Architectural Styles and Design Patterns

ADAPTER. Topics. Presented By: Mallampati Bhava Chaitanya

CS/CE 2336 Computer Science II

Brief Note on Design Pattern

Foundations of Software Engineering Design Patterns -- Introduction

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

Creational Patterns. Factory Method (FM) Abstract Factory (AF) Singleton (SI) Prototype (PR) Builder (BU)

An Introduction to Patterns

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

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

Object Oriented Paradigm

THOMAS LATOZA SWE 621 FALL 2018 DESIGN PATTERNS

Softwaretechnik. Design Patterns. Matthias Keil. Albert-Ludwigs-Universität Freiburg

INTERNAL ASSESSMENT TEST III Answer Schema

Introduction to Patterns and Frameworks

6.3 Patterns. Definition: Design Patterns

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

Softwaretechnik. Design Patterns. Stephan Arlt SS University of Freiburg. Stephan Arlt (University of Freiburg) Softwaretechnik SS / 47

LECTURE NOTES ON DESIGN PATTERNS MCA III YEAR, V SEMESTER (JNTUA-R09)

Software Engineering - I An Introduction to Software Construction Techniques for Industrial Strength Software

CS560. Lecture: Design Patterns II Includes slides by E. Gamma et al., 1995

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

Reuse at Design Level: Design Patterns

UNIT I Introduction to Design Patterns

Design Pattern and Software Architecture: IV. Design Pattern

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

EECS 4314 Advanced Software Engineering. Topic 04: Design Pattern Review Zhen Ming (Jack) Jiang

Applying Design Patterns to accelerate development of reusable, configurable and portable UVCs. Accellera Systems Initiative 1

Design Patterns. Lecture 10: OOP, autumn 2003

What are patterns? Design Patterns. Design patterns. Creational patterns. The factory pattern. Factory pattern structure. Lecture 10: OOP, autumn 2003

CSC207H: Software Design Lecture 6

Dr. Xiaolin Hu. Review of last class

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

CISC 322 Software Architecture

Design Patterns. Hausi A. Müller University of Victoria. Software Architecture Course Spring 2000

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

Design Patterns in Python (Part 2)

Review Software Engineering October, 7, Adrian Iftene

Intro to Patterns and Frameworks

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

Design patterns. Jef De Smedt Beta VZW

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

1 Software Architecture

UNIT I Introduction to Design Patterns

Design Patterns. Software Engineering. Sergio Feo-Arenis slides by: Matthias Keil

What is Design Patterns?

Design Patterns: Structural and Behavioural

Tuesday, October 4. Announcements

EMBEDDED SYSTEMS PROGRAMMING Design Patterns

Design pa*erns. Based on slides by Glenn D. Blank

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

SOFTWARE PATTERNS. Joseph Bonello

Design Patterns Reid Holmes

CS251 Software Engineering Lectures 18: Intro to DP

Design for change. You should avoid

3 Product Management Anti-Patterns by Thomas Schranz

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

Transcription:

Design Patterns

Acknowledgements Materials based on a number of sources D. Levine and D. Schmidt. Helm Gamma et al S. Konrad

Motivation Developing software is hard Designing reusable software is more challenging finding good objects and abstractions flexibility, modularity, elegance reuse takes time for them to emerge, trial and error Successful designs do exist exhibit recurring class and object structures

Design Pattern Describes recurring design structure names, abstracts from concrete designs identifies classes, collaborations, responsibilities applicability, trade-offs, consequences

Becoming a Chess Master First learn rules and physical requirements e.g., names of pieces, legal movements, chess board geometry and orientation, etc. Then learn principles e.g, relative value of certain pieces, strategic value of center squares, power of a threat, etc. To become a Master of chess, one must study the games of other masters These games contain patterns that must be understood, memorized, and applied repeatedly. There are hundreds of these patterns

Becoming a Software Design Master First learn rules e.g., algorithms, data structures, and languages of software. Then learn principles e.g., structured programming, modular programming, object-oriented programming, etc. To become a Master of SW design, one must study the designs of other masters These designs contain patterns that must be understood, memorized, and applied repeatedly. There are hundreds of these patterns

Design Patterns Design patterns represent solutions to problems that arise when developing software within a particular context Patterns == problem/solution pairs in a context Patterns capture the static and dynamic structure and collaboration among key participants in software designs Especially good for describing how and why to resolve nonfunctional issues Patterns facilitate reuse of successful software architectures and designs.

Design Patterns: Applications Wide variety of application domains: drawing editors, banking, CAD, CAE, cellular network management, telecomm switches, program visualization Wide variety of technical areas: user interface, communications, persistent objects, O/S kernels, distributed systems

What Is a Design Pattern (1) Each pattern describes a problem which occurs over and over again in our environment and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it in the same way twice Christopher Alexander, A Pattern Language, 1977 Context: City Planning and Building architectures

What Is a Design Pattern (2)

Pattern Name A handle used to describe: a design problem, its solutions and its consequences Increases design vocabulary Makes it possible to design at a higher level of abstraction Enhances communication But finding a good name is often difficult

Problem Describes when to apply the pattern Explains the problem and its context Might describe specific design problems or class or object structures May contain a list of conditions must be met before it makes sense to apply the pattern

Solution Describes the elements that make up the design, their relationships, responsibilities and collaborations Does not describe specific concrete implementation Abstract description of design problems and how the pattern solves it

Consequences esults and trade-offs of applying the pattern Critical for: evaluate design alternatives and understand costs and understand benefits of applying the pattern Includes the impacts of a pattern on a systemʼs: flexibility, extensibility portability

Design Patterns Are NOT Designs that can be encoded in classes and reused as is (i.e. linked lists, hash tables) Complex domain-specific designs (for an entire application or subsystem) They are: Descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context.

Where Design Patterns Are Used Object-Oriented Programming Languages: more amenable to implementing design patterns Procedural languages: need to define Inheritance, Polymorphism and Encapsulation

How to Describe Design Patterns Graphical notation is not sufficient In order to reuse design decisions, alternatives and trade-offs that led to the decisions are important Concrete examples are also important

A Design Pattern Describes a recurring design structure names, abstracts from concrete designs identifies classes, collaborations, responsibilities applicability, trade-offs, consequences

Observer Pattern Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically Key forces: There may be many observers Each observer may react differently to the same notification The subject should be as decoupled as possible from the observers allow observers to change independently of the subject

Structure of the Observer Pattern Subject Foreach o in observers loop o.update() End loop * Observer notify() attach(observer) detach(observer) update() Concrete Subject * Concrete Observer update() subject state get state() return subject_state subject -> get_state()

Collaboration in the Observer Pattern Concrete Subject Concrete Observer1 Concrete Observer2 set_state() notify() update() get_state() update() get_state()

Design Pattern Descriptions Main Parts: Name and Classification (see table in two more slides) Intent: Problem and Context Also known as (other well-known names) Motivation: scenario illustrates a design problem Applicability: situations where pattern can be applied Structure: graphical representation of classes (class diagram, interaction diagram) Participants: objects/classes and their responsibilities Collaborations: how participants collaborate Consequences: trade-offs and results Implementation: pitfalls, hints, techniques for coding; language-specific issues Sample Code Known Uses: examples of pattern in real systems elated Patterns: closely related; what are diffs. Pattern descriptions are often independent of programming language or implementation details

Design Pattern Space Creational patterns: Deal with initializing and configuring classes and objects Structural patterns: Deal with decoupling interface and implementation of classes and objects Composition of classes or objects Behavioral patterns: Deal with dynamic interactions among societies of classes and objects How they distribute responsibility

Categorize Design Patterns Purpose Scope Class Object Creational Structural Behavioral Factory Method Adapter (class) Interpreter Abstract Factory Builder Prototype Singleton Adapter (object) Bridge Composite Decorator Flyweight Facade Proxy Template Method Chain of esponsibility Command Iterator Mediator Memento Observer State Strategy Visitor

Categorization Terms Scope: domain over which a pattern applies Class Scope: relationships between base classes and their subclasses Static semantics Object Scope: relationships between peer objects Can be changed at runtime More dynamic

Purpose of Patterns Creational: Class: defer some part of object creation to subclasses Object: Defer object creation to another object Structural: Class: use inheritance to compose classes Object: describe ways to assemble classes Behavioral: Class: use inheritance to describe algs and flow of control Object: describes how a group of objects cooperate to perform task that no single object can complete

Terminology Signature: (of an operation) operation name, objects taken as parameters, and operationʼs return value Interface: (of an object) Set of all signatures defined by an objectʼs operations Characterizes the complete set of requests that can be sent to object. Key to OO technology

Creational Patterns Factory Method: method in a derived class creates associations Abstract Factory: Factory for building related objects Builder: Factory for building complex objects incrementally Prototype: Factory for cloning new instances from a prototype Singleton: Factory for a singular (sole) instance

Structural Patterns: Adapter: Translator adapts a server interface for a client Bridge: Abstraction for binding one of many implementations Composite: Structure for building recursive aggregations Decorator: Decorator extends an object transparently Facade: simplifies the interface for a subsystem Flyweight: many fine-grained objects shared efficiently. Proxy: one object approximates another

Behavioral Patterns Chain of esponsibility request delegated to the responsible service provider Command: request is first-class object Iterator: Aggregate elements are accessed sequentially Interpreter: language interpreter for a small grammar Mediator: coordinates interactions between its associates Memento: snapshot captures and restores object states privately Observer: dependents update automatically when subject changes State: object whose behavior depends on its state

Behavior Patterns (more) Strategy: Abstraction for selecting one of many algorithms Template Method: algorithm with some steps supplied by a derived class Visitor: operations applied to elements of a heterogeneous object structure

When to Use Patterns Solutions to problems that recur with variations No need for reuse if problem only arises in one context Solutions that require several steps: Not all problems need all steps Patterns can be overkill if solution is a simple linear set of instructions Solutions where the solver is more interested in the existence of the solution than its complete derivation Patterns leave out too much to be useful to someone who really wants to understand They can be a temporary bridge

What Makes it a Pattern A Pattern must: Solve a problem must be useful Have a context describe where the solution can be used ecur relevant in other situations Teach provide sufficient understanding to tailor the solution have a name referenced consistently

PAUSE

Class Scope Class Creational: abstract how objects are instantiated hide specifics of creation process may want to delay specifying a class name explicitly when instantiating an object just want a specific protocol

Example Class Creational Use of Factory Method: instantiate members in base classes with objects created by subclasses. Abstract Application class: create application-specific documents conforming to particular Document type Application instantiates these Document objects by calling the factory method CreateDocument Method is overridden in classes derived from Application Subclass DrawApplication overrides CreateDocument to return a DrawDocument object

Factory Method P r o d u c t C r e a t o r + F a c t o r M e t h o d ( ) + A n O p e r a t i o n ( ) p r o d u c t = F a c t o r y M e t h o d ( ) C o n c r e t e P r o d u c t C o n c r e t e C r e a t o r + F a c t o r y M e t h o d ( ) r e t u r n n e w C o n c r e t e P r o d u c t D o c u m e n t + O p e n () + C l o s e () + S a v e () + e v e r t () * 1 - d o c s A p p l i c a t i o n + C r e a t e D o c u m e n t ( ) + N e w D o c u m e n t ( ) + O p e n D o c u m e n t ( ) D o c u m e n t * d o c = C r e a t e D o c u m e n t ( ) ; d o c s. A d d ( d o c ) ; d o c - > O p e n ( ) ; D r a w A p p l i c a t i o n D r a w D o c u m e n t + C r e a t e D o c u m e n t ( ) r e t u r n n e w D r a w D o c u m e n t

Class Structural Class Structural: use inheritance to compose protocols or code Example: Adapter Pattern: makes one interface (Adaptee s) conform to another --> uniform abstraction of different interfaces. Class Adapter inherits privately from an Adaptee class. Adapter then expresses its interface in terms of the Adapteeʼs.

Adapter Example (class) Client Target equest() Adaptee Specificequest() Adapter equest() Drawing Editor Shape BoundingBox() CreateManip() TextView GetExtent() Line BoundingBox() CreateManip() TextShape BoundingBox() CreateManip() GetExtent()

Adapter Example (object) Client Target equest() Adaptee Specificequest() adaptee Adapter equest() Drawing Editor Shape BoundingBox() CreateManip() TextView GetExtent() Line BoundingBox() CreateManip() TextShape BoundingBox() CreateManip() Text eturn text --> GetExtent() eturn new TextManipulator

Class Behavioral Class Behavioral: capture how classes cooperate with their subclasses to satisfy semantics. Template Method: defines algorithms step by step. Each step can invoke an abstract method (that must be defined by the subclass) or a base method. Subclass must implement specific behavior to provide required services

Object Scope Object Patterns all apply various forms of non-recursive object composition. Object Composition: most powerful form of reuse euse of a collection of objects is better achieved through variations of their composition, rather than through subclassing.

Object Creational Creational Object Patterns: abstract how sets of objects are created Example: Abstract Factory: create product objects through generic interface Subclasses may manufacture specialized versions or compositions of objects as allowed by this generic interface User Interface Toolkit: 2 types of scroll bars (Motif and Open Look) Donʼt want to hard-code specific one; an environment variable decides Class Kit: encapsulates scroll bar creation (and other UI entities); an abstract factory that abstracts the specific type of scroll bar to instantiate Subclasses of Kit refine operations in the protocol to return specialized types of scroll bars. Subclasses MotifKit and OpenLookKit each have scroll bar operation.

Kit: Abstract Factory WidgetFactory CreateScrollBar() CreateWindow() Client MotifWindow Window OpenWindow MotifWidgetFactory CreateScrollBar() CreateWindow() OpenWidgetFactory CreateScrollBar() CreateWindow() Scrollbar MotifScroll OpenScroll

Object Structural Object Structural: Describe ways to assemble objects to realize new functionality Added flexibility inherent in object composition due to ability to change composition at run-time not possible with static class composition. Example: Proxy: acts as convenient surrogate or placeholder for another object. emote Proxy: local representative for object in a different address space Virtual Proxy: represent large object that should be loaded on demand Protected Proxy: protect access to the original object

Proxy Example Client * Subject Draw() GetExtent() Store() Load() DocumentEditor * Graphic Draw() GetExtent() Store() Load() ealsubject equest() realsubject Proxy equest() Image imageimp extent image Image Proxy filename extent Draw() GetExtent() Store() Load() Draw() GetExtent() Store() Load()

Object Behavioral Object Behavioral: Describe how a group of peer objects cooperate to perform a task that can be carried out by itself. Example: Strategy Pattern: objectifies an algorithm Text Composition Object: support different line breaking algorithms Donʼt want to hard-code all algs into text composition class/subclasses Objectify different algs and provide them as Compositor subclasses (contains criteria for line breaking strategies) Interface for Compositors defined by Abstract Compositor Class Derived classes provide different layout strategies (simple line breaks, left/right justification, etc.) Instances of Compositor subclasses couple with text composition at run-time to provide text layout Whenever text composition has to find line breaks, forwards the responsibility to its current Compositor object.

Object Behavioral Example Iterator Pattern: Iteration over a recursive structure Traversal strategies for a given structure: Extract and implement ea traversal strategy in an Iterator class. Iterators objectify traversal algs over recursive structures Different iterators can implement pre-order, in-order, post-order traversals equire nodes in structure to provide services to enumerate their sub-structures Donʼt need to hard-code traversal algs throughout classes of objects in composite structure Iterators may be replaced at run-time to provide alternate traversals.

Object Structural Example Facade Pattern (Wrapper): describes how to flexibly attach additional properties and services to an object Can be nested recursively; compose more complex object structures User Interface Example: A Facade containing a single UI component can add decorations such as border, shadows,scroll bars, or services (scrolling and zooming) Facade must conform to interface of its wrapped component and forward messages to it Facade can perform additional actions (e.g., drawing border around component) either before or after forwarding a message.

Benefits of Design Patterns Design patterns enable large-scale reuse of software architectures also help document systems Patterns explicitly capture expert knowledge and design tradeoffs make it more widely available Patterns help improve developer communication Pattern names form a vocabulary Patterns help ease the transition to OO technology

Drawbacks to Design Patterns Patterns do not lead to direct code reuse Patterns are deceptively simple Teams may suffer from pattern overload Patterns are validated by experience and discussion rather than by automated testing Integrating patterns into a SW development process is a human-intensive activity.

Suggestions for Effective Pattern Use Do not recast everything as a pattern Instead, develop strategic domain patterns and reuse existing tactical patterns Institutionalize rewards for developing patterns Directly involve pattern authors with application developers and domain experts Clearly document when patterns apply and do not apply Manage expectations carefully.