MSO Lecture 12. Wouter Swierstra (adapted by HP) October 26, 2017

Similar documents
MSO Object Creation Singleton & Object Pool

MSO Lecture 6. Wouter Swierstra. September 24, 2015

CPSC 310 Software Engineering. Lecture 11. Design Patterns

MSO Lecture 6. Wouter Swierstra (adapted by HP) September 28, 2017

CS342: Software Design. November 21, 2017

The Design Patterns Matrix From Analysis to Implementation

Agile Architecture. The Why, the What and the How

Index Shalloway rev.qrk 9/21/04 5:54 PM Page 419. Index

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

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

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

Lecture 13: Design Patterns

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

An Introduction to Patterns

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

Design Patterns Reid Holmes

EINDHOVEN UNIVERSITY OF TECHNOLOGY

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

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

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

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

MSO Exam November 7, 2016, 13:30 15:30, Educ-Gamma

A few important patterns and their connections

Plan. A few important patterns and their connections. Singleton. Singleton: class diagram. Singleton Factory method Facade

From Design Patterns: Elements of Reusable Object Oriented Software. Read the sections corresponding to patterns covered in the following slides.

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

CSC207H: Software Design Lecture 6

1 Software Architecture

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

Object-Oriented Design

Design Patterns. Gunnar Gotshalks A4-1

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

Tuesday, October 4. Announcements

Introduction to Design Patterns

Review Software Engineering October, 7, Adrian Iftene

Introduction to Design Patterns

Application Architectures, Design Patterns

Topics in Object-Oriented Design Patterns

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

Using Design Patterns in Java Application Development

Essential Skills for the Agile Developer. Agile. copyright Net Objectives, Inc.

Tutorial: Functions and Functional Abstraction. Nathaniel Osgood CMPT

CHAPTER 6: CREATIONAL DESIGN PATTERNS

What is Design Patterns?

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

Design Pattern and Software Architecture: IV. Design Pattern

Design patterns. Jef De Smedt Beta VZW

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

MSO Lecture Design by Contract"

Appendix A - Glossary(of OO software term s)

MSO Lecture 11. Wouter Swierstra (adapted by HP) October 23, 2017

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

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

CPSC 310: Sample Final Exam Study Questions 2014S1 (These are in addition to the Study Questions listed at the end of some lectures)

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

In this Lecture you will Learn: Design Patterns. Patterns vs. Frameworks. Patterns vs. Frameworks

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

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

More on Design. CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson

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

Design Patterns: Structural and Behavioural

DESIGN PATTERN - INTERVIEW QUESTIONS

Applying Some Gang of Four Design Patterns CSSE 574: Session 5, Part 3

Design patterns. OOD Lecture 6

Singleton Pattern Creational

What is a Pattern? Lecture 40: Design Patterns. Elements of Design Patterns. What are design patterns?

CS 351 Design of Large Programs Singleton Pattern

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

The GoF Design Patterns Reference

Object-oriented Software Design Patterns

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

Applying Design Patterns to SCA Implementations

VOL. 4, NO. 12, December 2014 ISSN ARPN Journal of Science and Technology All rights reserved.

Lectures 24 and 25 Introduction to Architectural Styles and Design Patterns

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

Software Design and Analysis for Engineers

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

An Introduction to Patterns

Object Oriented Paradigm

Design Patterns. An introduction

05. SINGLETON PATTERN. One of a Kind Objects

DESIGN PATTERNS FOR MERE MORTALS

Lecturer: Sebastian Coope Ashton Building, Room G.18 COMP 201 web-page:

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

Design Patterns. SE3A04 Tutorial. Jason Jaskolka

Responsibilities. Using several specific design principles to guide OO design decisions.

SOLID DESIGN PATTERNS FOR MERE MORTALS

Introduction to Software Engineering (2+1 SWS) Winter Term 2009 / 2010 Dr. Michael Eichberg Vertretungsprofessur Software Engineering Department of

Concurrency: State Models & Design Patterns

Design Patterns Thinking and Architecture at Scale

A - 1. CS 494 Object-Oriented Analysis & Design. UML Class Models. Overview. Class Model Perspectives (cont d) Developing Class Models

Template Method. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 24 11/15/2007. University of Colorado, 2007

MSO Lecture 11. Wouter Swierstra. October 15, 2015

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

A4 Explain how the Visitor design pattern works (4 marks)

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it

Object-Oriented Design

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

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

4.1 Introduction Programming preliminaries Constructors Destructors An example... 3

Transcription:

1 MSO Lecture 12 Wouter Swierstra (adapted by HP) October 26, 2017

2 LAST LECTURE Analysis matrix; Decorator pattern; Model-View-Controller; Observer pattern.

3 THIS LECTURE How to create objects

4 CATEGORIES OF DESIGN PATTERNS The Gang of Four distinguish three categories of design patterns: Behavioural patterns characterize the way in which classes or objects interact or distribute responsibility. Observer, Strategy Structural patterns deal with the composition of classes or objects. Adapter, Bridge, Decorator Creational patterns are concerned with the creation of new objects. Abstract Factory (Shalloway and Trott also distinguish a decoupling category, which forms a subset of the behavioural patterns).

5 WHY WORRY ABOUT CREATION? A lot of the design we have focussed on so far in this course is concerned with figuring out how classes should work together, and how to encapsulate variation hiding implementation details. But if we hide implementation details behind an abstract class, who decides which concrete instances should be made?

6 FACTORIES Separating creation and usage leads to stronger cohesion. Separate two distinct tasks: Defining classes and how they work together Writing factories that instantiate the correct objects for the right situation.

7 NOT EVERYONE AGREES... Remember Larman s Creator GRASP principle: Assign class B the responsibility to create instances of a class A if A has a B object. This is a good guideline for simple situations, provided you are not programming to an interface. If you are, you may need to consider applying creational design patterns.

8 CREATION VS USE Shalloway and Trott say that an object should either: make and/or manage other objects; or it should use other objects. It should never do both. Following this rule leads to looser coupling.

9 USING OBJECTS "Program to an interface, not to an implementation" "Find what varies, and encapsulate it" Using Object AbstractClass Concrete ClassA Concrete ClassA

10 EXAMPLE: STRATEGY If the Context creates concrete strategies, it s breaking an abstraction barrier. Instead, we want to assign the responsibility for creation to another object.

11 FACTORY OBJECTS Compare figure 20-3 on page 352 of S&T.

12 USING VS CREATING OBJECTS The Factory can create values of type AbstractClass on request. It stores all the creational logic and creates a concrete object. Using objects means knowing only about the interface, not the implementation. The Factory objects should only know how to create concrete instances. They should not rely on the details of the abstract class/interface. We are free to add new concrete classes as necessary we know that the client objects should never inspect which concrete class they are using the Open-Closed principle!

13 SUMMARY Patterns add indirection (hide information behind an abstract class, move functionality to new classes,... ) This makes code more maintainable, but adds complexity. Factories and other creational patterns are designed to hide the complexity that patterns sometimes introduce.

14 THE SINGLETON PATTERN Factories can be used for more than just controlling which concrete instances to create. For instance, factories may implement constraints. The Singleton Pattern for example, can be used to guarantee that exactly one object exists of a particular type.

15 THE SINGLETON PATTERN Singleton - instance : Singleton - singletondata - Singleton() + static getinstance() + operation... + getdata

16 THE SINGLETON PATTERN public class Singleton { private static Singleton instance; private Singleton() {... } } public static Singleton getinstance() { if (instance == null) { instance = new Singleton(); } return instance; }

17 SINGLETON: EXAMPLE One example of a Singleton could be the CalcTax strategy for a specific country. Another example of a Singleton could be a logging service: Different objects want to be able to log a message. They want a single point of entry to send their logging requests we do not want to create new services for each request.

18 CAUTION! Singletons are not thread safe. If you have multiple threads trying to create a singleton at the same time, you may create two (or more) Singleton objects. Solution: The Double-Checked Locking Pattern addresses this. I will not cover it in this course.

19 MORE CAUTION! Singletons are a controversial pattern. The Singleton is regarded to be an over applied pattern - it is often not even needed. To decide whether a class is truly a singleton, you must ask yourself some questions: Will every application use this class exactly the same way? Will every application ever need only one instance of this class? (Rainsberger 2001) So much for singletons.

20 CASE STUDY: ELECTRONIC BANKING Today let s suppose we need to write software for online investment services, like alex.nl, that allow users: to browse their investment portfolio; to give orders for purchasing or selling stocks;... We will see that Factory tasks may be a bit more involving than just creating objects!

21 ARCHITECTURE Java Servlet CORBA C++ Middleware TCP/IP Mainframe

22 REQUIREMENTS The only way to communicate with the mainframe is through TCP/IP connections using a custom messaging protocol. The C++ (or C#, or...) middleware is responsible for verifying user orders, before they are executed by the mainframe.

23 EXAMPLE INTERACTION User logs in through their webbrowser. Middleware gets user ID and password. Reformats message in a format the mainframe can understand. Mainframe accepts the request and responds accordingly.

24 PERFORMANCE CONCERNS The middleware needs to handle requests from many, many people at the same time; We should aim to handle as many transactions as possible - aim to maximize throughput - and not worry about the time a single transaction needs.

25 DESIGN QUESTION How many TCP/IP connections should I use? 1 is too little all traffic goes over a single connection; 100 is too much the bandwidth available could not handle more than 20. This is a high-risk issue. The performance of the entire system can rely on it.

26 ISSUES INVOLVED Establish a single, robust TCP/IP connection. Determine the number of TCP/IP connections that are necessary. Establish a method to load balance the connections we don t want to route all traffic through a single connection, while the others idle. Handle errors on TCP/IP connections, as these can be unreliable. What to do first?

27 DESIGN CHOICE Start by establishing a single connection but don t forget that you will have to address these other issues soon. General strategy: insulate yourself from change, but anticipate new requirements.

28 CHOOSING THE CONNECTIONS We need to design the system so that we can easily change the number of connections used. So who is responsible for establishing the connections? Someone else. Find what varies and encapsulate it.

29 TCP/IP MANAGEMENT We need a class to manage the TCP/IP connections. Should this be the connection class itself?

30 TCP/IP MANAGEMENT Distinguish separate responsibilities: A Port class is responsible for communicating with the mainframe; A PortManager class is responsible for keeping track of the Ports.

31 HOW MANY? There should be multiple Port objects. The PortManager should be able to change the exact number easily. There should only be a single PortManager object otherwise we don t have control over how many connections are established exactly. Use the Singleton pattern!

32 FUNCTIONALITY The PortManager supports has the following methods and attributes: a private array of Port objects; GetInstanceOfPort() - which looks through the array to find an inactive port. If no port is inactive, it sleeps and retries. ReturnInstanceOfPort(Port release) - sets the status of the argument port to inactive.

33 USING PORTS Client code is now straightforward: 1. Ask the PortManager for a Port object; 2. Complete the transaction. 3. Release the Port to the PortManager. The client code does not need to know anything about how many ports are active, setting up connections, etc.

34 STRONG COHESION, LOOSE COUPLING This solution has strong cohesion and loose coupling the Port, Client, and PortManager classes all have a clear set of responsibilities. What happens when I need to add error handling?

35 ADDING ERROR HANDLING What happens when a connection goes down? 1. The Client code needs to request another Port; 2. The Port that went down should be closed; 3. The PortHandler may want to establish a new connection to replace the Port that want down. It is clear who is responsible for handling this exceptional scenario.

36 ARE WE DONE? If you re responsible for developing a system that handles millions of dollars worth of transactions, will you sleep easy at night?

37 ADD CHECKING Maybe we would sleep easier if the PortManager also checked the integrity of the connection. Every 15 (or so) minutes it should: 1. Check how many unanswered requests there are for a Port; 2. Query all the Ports to see if they are active or not; 3. Check how many Ports have run into an error. If any of these checks produces unexpected results, warning bells should go off.

38 EVEN BETTER... Don t stop there! It s not enough to know that a system is not failing. Perhaps you cannot detect connection problems, but people still are not able to use the website. Log successful transactions.

39 THE OBJECT POOL PATTERN Client 0..* 1 Uses * Reusable 0..* ReusablePool -ReusablePool() +getinstance() +acquirereusable() : Reusable +releasereusable(r : Reusable) +setsize(maxsize : int) 1 1 Note that getinstance() refers to the creation of a singleton ReusabePool.

40 THE OBJECT POOL PATTERN: LESSONS Factories are not just about instantiation.

41 TWO MORE PATTERNS Template Method Pattern Factory Method Pattern We will look see them working in an integrated way.

42 CASE STUDY: DATABASES The Template Method pattern can be very useful when a certain kind of computation has a lot of variation - it allows us to encapsulate this variation. preparequery(query1);... if (database == ORACLE) conn = formatoracleconnect(); else conn = formatsqlserverconnect(); if (database == ORACLE) res = formatoracleselect(conn, query1); else res = formatsqlserverselect(conn, query1); processresults(res);

43 CASE STUDY: DATABASES Suppose we need to write software that generates SQL queries on different databases (both Oracle and SQL Server). In principle the queries have the same structure: 1. Format the CONNECT command. 2. Send the database the CONNECT command. 3. Format the SELECT command. 4. Send the database the SELECT command. 5. Return the answer from the database.... but there is slight variation in the formatting procedures for the different database backends.

44 TEMPLATE METHOD: INTENT The Gang of Four define the intent of the Template Method Pattern as: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Redefine the steps in an algorithm without changing the algorithm s structure. This sounds similar to our database problem...

45 TEMPLATE METHOD QueryControl Query Template + doquery() # formatconnect() # formatselect() Oracle Query Template # formatconnect() # formatselect() SQLServer Query Template # formatconnect() # formatselect()

46 WHERE THE MAGIC HAPPENS The QueryTemplate class defines the following method: public doquery(string q) {... c = formatconnect();... res = formatselect(c, q); processresults(res); } An abstract class (QueryTemplate) defines a public, concrete method (doquery), that itself calls abstract, protected methods (formatselect and formatconnect).

47 CODE-BASED CVA Template Methods are a great way to clean up duplicated methods, or fixing code that has been copy-pasted and edited. 1. Look for the common parts these go in the abstract class. 2. Look for the variation these go in the concrete instances.

48 TEMPLATE METHOD I Intent: Define the skeleton of an algorithm, deferring some steps to subclasses, making it possible to redefine some of the steps in the algorithm, without changing the algorithm s structure. Problem: There is a procedure or set of steps that is consistent at one level of detail, but individual steps may have different implementations. Solution: Allows for a definition of substeps that vary while maintaining a consistent basic process. Participants: The Template Method defines an abstract class with a concrete method, that uses abstract methods that need to be overridden.

49 TEMPLATE METHOD II Consequences: Templates provide a good platform for code reuse. They are also helpful in ensuring the required steps are implemented. Implementation: Template + TemplateMethod() # operation1() # operation2() Concrete Template A # operation1() # operation2() Concrete Template B # operation1() # operation2()

50 CREATION? In our case study, the Template Method pattern showed how to handle variation in database communication. An abstract QueryTemplate object hides implementation details. But who creates the associated database object?

51 ASSIGNING RESPONSIBILITY If the database creation varies between the two Template subclasses (for Oracle or SQL Server databases), the subclasses should be responsible.

52 QueryControl Query Template + doquery() # formatconnect() # formatselect() # makedatabase() Oracle Query Template # formatconnect() # formatselect() # makedatabase() SQLServer Query Template # formatconnect() # formatselect() # makedatabase()

53 WHAT DOES THIS ACHIEVE? The QueryTemplate class does not know which database is created. It just knows that all concrete derived classes will define a method to create a database object. The derived classes are responsible for the creation. This is called the Factory Method pattern, which is used heavily in C# collections libraries.

54 FACTORY METHOD: INTENT The Gang of Four define the intent of the Factory Method Pattern: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

55 FACTORY METHOD Product Creator MakeProduct() Operation() Concrete Product Concrete Creator MakeProduct()

56 FACTORY METHOD Product Creator MakeProduct() Operation() Concrete Product Concrete Creator MakeProduct() Example: (book is vague on this issue) Creator <=> Query Template MakeProduct() <=> MakeDatabase() Operation() <=> logic in creation process

BACK TO SALESORDER AND CALCTAX Let us recall our Salesorder - CalcTax example. We applied the Strategy pattern. But the logic for choosing the concrete strategy object was still part of the Context. We could add a public method makecalctax(customer c) to the interface of Strategy. This way, we combine patterns Strategy and Factory Method. 57

58 OVERVIEW 1. Identifying objects based on responsibilities (CVA, Analysis matrix, noun-verb analysis, GRASP). 2. Deciding how to use these objects (design patterns). 3. Deciding how to manage these objects (factories).

59 PHILOSOPHY BEHIND FACTORIES Conceptually similar objects are often used in the same way. When creating these objects, there is some logic involved that decides to choose one specific concrete class. The using class should not know which specific concrete class it is using it should program to an interface, not an implementation. So if the using class cannot choose how to instantiate objects, someone must be responsible - enter Factories.

60 FACTORIES AND CHANGING REQUIREMENTS In practice most new requirements affect either the users of an object or system (or its internal implementation) or the logic controlling the choice of which objects to create It is much less common that both these things need to change.

61 GOLDEN RULE OF OBJECT CREATION Try to make an object responsible for using or creating, but never both.

62 LAST WEEK Next week Monday guest lecture by Jan Martijn vd Werf Next week Thursday no lecture, but there is lab assistance Come to the guest lecture! Learn!

63 MATERIAL COVERED Design Patterns explained. Chapter 19-24