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

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

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

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

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

SDC Design patterns GoF

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

Topics in Object-Oriented Design Patterns

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

Using Design Patterns in Java Application Development

Design Patterns. An introduction

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

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

Design Patterns Reid Holmes

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

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

Object-Oriented Design

Tuesday, October 4. Announcements

Software Eningeering. Lecture 9 Design Patterns 2

Design Patterns Lecture 2

Object Oriented Methods with UML. Introduction to Design Patterns- Lecture 8

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

Object-Oriented Oriented Programming

DESIGN PATTERN - INTERVIEW QUESTIONS

Design Patterns. CSC207 Fall 2017

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

Design Patterns. CSC207 Winter 2017

What is Design Patterns?

Introduction to Software Engineering: Object Design I Reuse & Patterns

SOFTWARE PATTERNS. Joseph Bonello

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

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

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

Design Patterns. CSC207 Fall 2017

Object Oriented Paradigm

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

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

Lecture 20: Design Patterns II

Design patterns. Jef De Smedt Beta VZW

Object-oriented Software Design Patterns

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

Applying the Observer Design Pattern

Design Patterns Reid Holmes

Design Patterns. SE3A04 Tutorial. Jason Jaskolka

An Introduction to Patterns

The GoF Design Patterns Reference

Design Patterns: Structural and Behavioural

Brief Note on Design Pattern

APPLYING DESIGN PATTERNS TO SCA IMPLEMENTATIONS

An Introduction to Patterns

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

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

1 Software Architecture

Application Architectures, Design Patterns

Design patterns. OOD Lecture 6

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

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

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

A Reconnaissance on Design Patterns

Design Patterns. Gunnar Gotshalks A4-1

be used for more than one use case (for instance, for use cases Create User and Delete User, one can have one UserController, instead of two separate

Applying the Factory Method Design Pattern

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

Lectures 24 and 25 Introduction to Architectural Styles and Design Patterns

Object-Oriented Design

3 Product Management Anti-Patterns by Thomas Schranz

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

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

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

What is Design Patterns?

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

Applying the Decorator Design Pattern

A Primer on Design Patterns

Review Software Engineering October, 7, Adrian Iftene

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

Lecture 13: Design Patterns

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

Second Midterm Review

Pattern Resources. Lecture 25: Design Patterns. What are Patterns? Design Patterns. Pattern Languages of Programming. The Portland Pattern Repository

Summary of the course lectures

Design Patterns IV Structural Design Patterns, 1

Software Engineering I (02161)

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

Design Pattern and Software Architecture: IV. Design Pattern

6.3 Patterns. Definition: Design Patterns

The Object Recursion Pattern

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

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

Information systems modelling UML and service description languages

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

Composite Pattern. IV.4 Structural Pattern

Chapter 8, Design Patterns Visitor

Topics. Software Process. Agile. Requirements. Basic Design. Modular Design. Design Patterns. Testing. Quality. Refactoring.

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

MVC. Model-View-Controller. Design Patterns. Certain programs reuse the same basic structure or set of ideas

ADAPTER. Topics. Presented By: Mallampati Bhava Chaitanya

A Rapid Overview of UML

The Design Patterns Matrix From Analysis to Implementation

Design Patterns. (and anti-patterns)

Applying Design Patterns to SCA Implementations

What is Design Patterns?

Transcription:

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

Design Patterns Design patterns take the problems consistently found in software, and look to solve them using a reusable design. These patterns describe the way code is laid out, rather than the exact code that would be required This implies that design patterns are language agnostic to a degree We can use UML to easily describe these patterns both structurally and functionally These patterns also represent a means to communicate design decisions which may have been made by other developers, in a common and clean way. It is important to get used to recognizing these within a given code base.

Design Patterns First published in a book titled Design Patterns: Elements of Reusable Object-Oriented Software in 1994, although the concept had been around since the late 70 s. The book was published by the Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides) The original book had 23 patterns, there have been many more created since. The patterns are split in three main groups: Creational Patterns that deal with the mechanics of object creation Structural Patterns that deal with creating simple ways of building relationships between objects Behavioural-Patterns that deal with common communication between objects

Design Patterns Slide Layout For the next several lectures, we will be diving into each of the patterns laid out by the gang of four in detail. For each pattern, we will discuss its intended use, the motivation of the pattern, the UML that describes it, and the situations to look for when using it. For some patterns, we will also be going into specific examples in Java or Python, as well as consequences of using it, and common or known issues with the use of the pattern.

Gang of Four Patterns Original book describes 23 patterns 5 Creational, 7 Structural, and 11 Behavioural. Creational Patterns Behavioural Patterns Structural Patterns Abstract Factory Chain of Responsibility Adapter Builder Command Bridge Factory Method Interpreter Composite Prototype Iterator Decorator Singleton Mediator Façade Memento Flyweight Observer Proxy State Strategy Template Method Visitor

Observer (B) Problem Need to maintain consistency between related classes Two aspects that are dependent upon one another Objects should be able to updated related objects without requiring specific knowledge of those objects Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and update automatically Consequences There is only light, abstract coupling between the Subject and Observer. Since the Subject only knows it has a list of Observers whom conform to the simple Observer Interface Broadcast messaging is achieved, as the Subject does not need to specify the receiver of the message Not easy to trace the cost of an update, as everything is so loosely coupled at a design level, but is highly interdependent at an operation level. Each change to the Subject may cause large cascading changes throughout application, if not carefully controlled for Related Patterns Mediator, Singleton

Observer Standard Solution

Observer Java Implementation Although Java does provide a default Observer implementation, it does so through an abstract class. This removes the ability to use it alongside custom hierarchies, as Java does not have multiple inheritance. For this reason, most implement their own version of the pattern classes using interfaces.

Observer Example in Java

Observer Sequence Diagram The standard sequence diagram for Observer is shown to the right. You may also see this drawn without the Par tag.

Singleton Pattern (C) Problem How do you ensure that only one instance of a class ever exists? Is there a way to ensure that an object is only created if it is needed? Intent Ensure a class only has one instance and provide a global point of access for it Consequences Strict control on access since the singleton has only one point of entry, this can be easily monitored and controlled Reduced namespace The pattern removes pollution of the global namespace by unnecessary repetition Recent thoughts on Singleton A large number of software engineers now consider Singleton to be a design smell, something that is off in the system. Seeing it used often means something was not well thought out. A notable person with this thought is Erich Gamma, the original creator of the pattern Related Patterns Many patterns can use singleton in their implementation, but this is becoming frowned upon

Singleton Standard Solution

Iterator Pattern (B) Problem Want to be able to see the objects stored within an aggregator sequentially, but do not want to expose the underlying representation Want to have the ability to iterate over the same aggregation in different, independent ways Intent Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation Consequences Supports variations in the traversal of an aggregate. Complex aggregates may be traversed in many ways Iterators simplify the aggregate interface by removing details about traversal More than one traversal can be pending on an aggregate. Iterators only keep track of their own traversal state, and thus, multiple traversals can be occurring in unison Related Patterns Composite, Factory Method, Memento

Iterator Pattern Standard Solution

Iterator in Java In java, you will notice that Iterators are most commonly seen with classes that have generics. The iterator pattern is implemented in Java already through the Iterator Interface within java.util package Since Java 5, using the Java Iterable interface allows for you to use foreach loops

Strategy Pattern (B) Problem Having multiple classes that only differ in the algorithms used on them (behaviour) Algorithms shouldn t be implemented directly within the class Intent Define a family of algorithms, encapsulating each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it Consequences Families of related algorithms emerge these can be factored out using class hierarchies within the strategies An alternative to sub-classing Sometimes algorithmic differences are only difference between parent and children classes, Strategy removes the need to create specific children Eliminate conditional statements By delegating the choice to the composite class, remove the need for if blocks Choice of implementation Client can pick between multiple strategies that have different time or space trade-offs Clients must be aware of different strategies The pattern can potentially create issues if client doesn t have full awareness Communication overhead between strategy and context Context can create large overhead for simple algorithms that don t need the full set of information that other more complex algorithms need Increased number of objects As each strategy requires its own class, the number of objects can increase Related Patterns Flyweight Strategy often makes good Flyweights

Strategy Pattern Standard Solution

Example Without Strategy Pattern

Using Strategy Pattern

Façade Pattern (S) Problem Want a way to hide the complexity of an underlying package from those who use it Some programs have complexities we want to hide from other users Intent Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystems easier to use. (NOTE: In this context interface does not mean an interface type object such as we have in Java, but a point of communication between two areas) Consequences Clients are shielded from subsystem objects, reducing scope of what they need to understand Promotes weak coupling, between subsystems and clients of that system It doesn t explicitly prevent direct use of subclasses, but gives an alternative. Related Patterns Abstract Factory, Mediator, Singleton

This is a Façade

Façade Standard Solution The Façade does not add any new functionality, nor does it remove previously available functionality. It simply gives an easy to use interface into a subsystem that may have been previously difficult to understand.

Façade - Example

Adapter Pattern (S) Problem Clients often want things in a format other than what we have, but we do not want to recreate our classes Lets classes work together that otherwise couldn t easily work together by creating an agreed interface Two primary forms: Class adapter (using multiple inheritance) and Object adapter (using object composition) Intent Convert the interface of a class into another interface to meet a clients demand/expectation. Adapter lets classes work together that couldn t otherwise because of incompatible interfaces Consequences Each of the two versions have different consequences which will be broken down on the following slide Related Patterns Bridge, Decorator, Proxy

Adapter Two Forms Class Adapter Adapts Adaptee to Target by committing to a concrete Adaptee class. As a consequence, a class adapter won t work when we want to adapt a class and all its subclasses Allows for overriding the Adaptee s behaviour Object Adapter Lets a single adapter work with many adaptees, for example, all subclasses of the adaptee as well as the adaptee itself Makes it difficult to override the methods of the adaptee Consequences How much adapting should be done It can be difficult where to draw the line for when this is an appropriate pattern and when it will end up ultimately creating more work Pluggable adapters a class is more resuable if you minimize the assumptions other classes make to use it. The term refers to building in adapters from the onset Using two-way adapters currently adapter does not allow for two-way adaptation, and it isn t transparent to the client what is happening. This can lead to suboptimal situations

Adapter Standard Solution Class Adapter Object Adapter

Adapter - Example PROBLEM Suppose there is a shortage of Ducks, and in their place we want to use Penguins, as I mean, they are pretty close What cannot be done Direct substitution of Penguins where we have Ducks. Ducks have some distinctive differences from Penguins, and thus have a different interface! Solution Write a PenguinAdapter class! (Can you even tell which is which?)

Adapter - Example

Adapter - Example

Factory Method Pattern (C) Problem Creating new objects often requires complex logic, which we d ideally like to mask from our clients Often we want to create objects in a fixed way but don t want to store this fixed logic inside the calling class as this creates stronger coupling Intent Define an interface for creating an object but let subclasses decide which class to instantiate. Factory method allows classes to differ instantiation to subclasses Consequences Provides hooks for subclasses Creating objects in a class with a factory method is more flexible Connects parallel class hierarchies Factory methods can be called from either creators or from parallel classes Related Patterns Abstract Factory, Template Method, Prototype

Factory Method Standard Solution

Factory Method - Example

Abstract Factory Pattern (C) Problem Systems should be independent of how their objects are created, composed, or represented A family of related products are designed to be used together, and you need to enforce this constraint Intent Provide an interface for creating families of related or dependent objects without specifying their concrete classes Consequences It isolates concrete classes You can remove the use of concrete class names in client code, meaning if you need to change a concrete implementation, the client never needs to know It makes exchanging product families easy Switching out abstract factories can result in a new functionality without much code change at all It promotes consistency among products as all products will follow a similar design, you end up with more consistent classes Extending product families (new products in same family) is very difficult this is because the abstract factory defines all the products it can create. Adding becomes a major change. Related Patterns Factory Method, Prototype, Singleton

Abstract Factory Standard Solution

Abstract Factory - Example

Abstract Factory Example in Java For this example, we want to give users the ability to at runtime decide if they want the shapes they are seeing to be displayed as text names for the shapes, or ASCII drawings of the shapes. The user will provide a console input of 0 if they want the drawings, and 1 if they want text.

Factory Pattern (C) NOTE: Not an official pattern Motivation There is often a need to use some of the elements of Factory Method, and some of the elements of Abstract Factory, without implementing to the totality of both. This is often referred to as the Factory Pattern.

Factory Example In this example, assume we have an application for calculating the cost of a construction project. TaxCalculator calculates the tax on our specific items. Quebec and Ontario have different tax rates and rules, and thus need to be handled differently. We may eventually also want to add another province into the project.

Decorator Pattern (S) Problem Sometimes we want to give additional responsibilities to an object after it s been defined Want this to be done without impacting other objects When it s impractical to subclass due to the combinatorial explosion of possibilities Intent Attach additional responsibilities to an object dynamically. Decorators allow for a flexible alternative to subclassing when there is a need to extend functionality Consequences More flexibility than static inheritance The decorator pattern provides a more flexible way to add responsibilities to objects Avoids feature-laden classes high up in the hierarchy decorator offers a pay-as-you-go approach to adding responsibilities to classes Lots of little objects these can be a mess to deal with. Can become very complex to debug Related Patterns Adapter, Composite, Strategy

Decorator Standard Solution

Decorator Example Problem Problem There are many types of pizza, and many different combinations of what can be on a pizza Crust thin, thick, whole wheat Toppings cheese, tomato, anchovies, pineapple, Solution Inheritance? But where is the pineapple??

Decorator Example Solution New toppings? Not to worry! Just create another little subclass to PizzaDecorator

Decorator Example Solution How exactly is this working? Let s take a quick walkthrough of the code. This is a very simplistic version, but gives you a good general understanding. Finally, would this differ in Python?

Chain of Responsibility Pattern Problem Sometimes we have multiple classes that can handle a potential request, and do not know a priori which handler should be used We want to issue a request to one of several potential objects but do not want to explicitly specify the receiver The objects to handle a request should be specified dynamically Intent Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. Consequences Reduced Coupling The pattern frees an object from knowing which other object handles a request. Added flexibility in assigning responsibility Since the chain can be modified at runtime, you have control over how requests are handled, and can even change based on context Receipt isn t guaranteed Since a request has no explicitly defined receiver there is no guarantee it ll be handled. A request can fall off the end of the chain without being handled. This is usually a configuration issue Related Patterns Often implemented with Component pattern to keep track of the chain of successors

Chain of Responsibility - Standard Solution A typical object structure looks something like this:

Chain of Responsibility - Java Let s implement a simple chain of responsibility in Java. This chain will be built with a series of loggers. One logger will log to stdout, and another to stderr. Once we understand this chain, we will add a third logger which will output to stdout with a different message than the original stdout logger. Finally, we will draw the command chains for each of the loggers we have setup, as well as the sequence diagram for them on the board.

Visitor Pattern (B) Problem You have an object structure with many classes and interfaces and you want to perform operations on these classes that logically should be together We don t want to pollute our object structures with many distinct and unrelated operations. We want to use objects across multiple applications, but some operations are not needed by all applications Our objects are not changing frequently, but the operations we want to apply are Intent Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. Consequences As there are many important consequences to visitor, they will be covered in the slide after the basic UML and sequence diagrams for Visitor. Related Patterns Composite, Interpreter

Visitor Pattern Standard Solution Note: The Accept(Visitor v) operations will in turn call upon the VisitConcreteElement method with itself as a parameter, giving the visitor full access to the Element s object structure.

Visitor Pattern Sequence Diagram

Visitor Pattern - Consequences Consequences Visitor makes adding new operations easy visitors can be easily created to be run across many objects A visitor gathers related operations and separates unrelated ones you end up with tighter coupling behaviourally, meaning if a behaviour needs modification, it s located in a single place Adding new concrete objects is hard since you need to make a new operation for this object in all visitor classes. You need to make the decision if you will be frequently changing your algorithms or your object structure Visiting can occur across classes Unlike Iterator, that requires each visited node to be of the same type, Visitors can visit classes which are not in the same hierarchy, as long as they have an accept method, and a subsequently appropriate Visit method defined Accumulating state visitors can take on the responsibility of accumulating the state of each element in the object structure. Without this, the state would have to be stored and passed independently Breaking Encapsulation One of the key consequences of visitor is that it requires you to build public methods which have access to state variables within the class directly. This can easily end up breaking the encapsulation of your code!

Visitor Pattern - Example Problem We have a well-defined (and not likely to change) structure called an Abstract Syntax Tree Abstract Syntax Tree has various node types, including Variable assignment. A compiler needs to perform various operations on it, including type checking and code generation. Task Use the Visitor pattern to solve the above

Visitor Pattern Example Solution

Visitor Pattern Another Example Problem When you buy groceries in the supermarket, they come in various types: some need to be weighed, others have a barcode that can be scanned, etc. When it is time to pay, the cash computer will calculate the total price, print a receipt, etc. Task Use the Visitor design pattern to design a solution. How does it work? Show a sequence diagram. How does it work? Show skeleton of Java code.