c++ training datascope lawrence d’antonio lecture 12 design patterns

46
Datascope Datascope Lawrence Lawrence D’Antonio D’Antonio Lecture 12 Lecture 12 Design Patterns Design Patterns

Post on 18-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

C++ TrainingC++ TrainingDatascopeDatascope

Lawrence D’AntonioLawrence D’AntonioLecture 12Lecture 12

Design PatternsDesign Patterns

Page 2: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

What are patterns?What are patterns?

Patterns may be thought of as solutions to Patterns may be thought of as solutions to recurring problems. recurring problems.

They tell us what should be done when They tell us what should be done when confronting a known problem in a given confronting a known problem in a given context. context.

Also, just as patterns tell us what to do, Also, just as patterns tell us what to do, there exist anti-patterns which tell us what there exist anti-patterns which tell us what not to do in certain situations. not to do in certain situations.

Page 3: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Origins of PatternsOrigins of Patterns

The concept of patterns as playing a key The concept of patterns as playing a key role in the design process arises from the role in the design process arises from the work of the architect Christopher work of the architect Christopher Alexander. Alexander.

For Alexander, the difference between For Alexander, the difference between good architecture and bad architecture is good architecture and bad architecture is an objective one. Patterns are a way of an objective one. Patterns are a way of capturing this difference. capturing this difference.

Page 4: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Patterns, with their emphasis on solutions Patterns, with their emphasis on solutions to recurring problems, reveal underlying to recurring problems, reveal underlying structure in the problem domain, support structure in the problem domain, support the principles of software reuse, and most the principles of software reuse, and most importantly, generate solutions to importantly, generate solutions to problems. problems.

Patterns show us at the same time the Patterns show us at the same time the flashpoints of a system and what to do flashpoints of a system and what to do about them. about them.

Page 5: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Good design works to the benefit of its Good design works to the benefit of its users. This human side to design, users. This human side to design, emphasizing its wholeness, harmony, emphasizing its wholeness, harmony, completeness, endurance, and vitality, is completeness, endurance, and vitality, is too often overlooked (in buildings and in too often overlooked (in buildings and in software). software).

Page 6: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Christopher AlexanderChristopher Alexander

Page 7: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Alexander’s BooksAlexander’s Books

Page 8: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns
Page 9: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Alexander’s definition of patternAlexander’s definition of pattern

““Each pattern is a three-part rule, which Each pattern is a three-part rule, which expresses a relation between a certain expresses a relation between a certain context, a problem, and a solution.”context, a problem, and a solution.”

Page 10: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

““The pattern is, in short, at the same time The pattern is, in short, at the same time a thing, which happens in the world, and a thing, which happens in the world, and the rule which tells us how to create that the rule which tells us how to create that thing, and when we must create it.“thing, and when we must create it.“

Page 11: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

““It is both a process and a thing; both a It is both a process and a thing; both a description of a thing which is alive, and a description of a thing which is alive, and a description of the process which will description of the process which will generate that thing.”generate that thing.”

Patterns establish relations between Patterns establish relations between objects in particular contexts. objects in particular contexts.

So that if the same context arises again So that if the same context arises again then we expect to see the same then we expect to see the same relationships. relationships.

Page 12: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

In shortIn short

"A pattern is a solution to a problem in "A pattern is a solution to a problem in context.“context.“

Patterns establish relations between Patterns establish relations between objects in particular contexts. objects in particular contexts.

So that if the same context arises again So that if the same context arises again then we expect to see the same then we expect to see the same relationships. relationships.

Page 13: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Simple exampleSimple example

"Where a freeway meets an artery the "Where a freeway meets an artery the access ramps of the interchange take the access ramps of the interchange take the rough form of a cloverleaf.“rough form of a cloverleaf.“

The Interchange pattern explains to the The Interchange pattern explains to the architect how to build an interchange.architect how to build an interchange.

Page 14: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns
Page 15: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

CS exampleCS example

Call by Reference pattern Call by Reference pattern This pattern states that when large objects This pattern states that when large objects

are passed on the stack (or small objects are passed on the stack (or small objects passed frequently) then the call should be passed frequently) then the call should be done by reference rather than by value. done by reference rather than by value.

The Call by Reference pattern explains to The Call by Reference pattern explains to the student programmer how to pass large the student programmer how to pass large objects. objects.

Page 16: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Alexandrian PatternsAlexandrian Patterns

Patterns have the following components:Patterns have the following components: Problem, Context, Forces, Solution, Problem, Context, Forces, Solution,

Examples, Resulting Context, RationaleExamples, Resulting Context, Rationale

Page 17: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

ProblemProblem

A set of goals and objectives within a A set of goals and objectives within a given context and with a given set of given context and with a given set of constraints. This describes the intent of constraints. This describes the intent of the system.the system.

Page 18: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

ContextContext

The initial state (or configuration) of the The initial state (or configuration) of the system prior to applying the pattern. system prior to applying the pattern.

The pattern will solve the given problem The pattern will solve the given problem only if it is applied in the appropriate only if it is applied in the appropriate context. context.

Once a pattern becomes known, the Once a pattern becomes known, the context is a signpost for applying the context is a signpost for applying the pattern. pattern.

Page 19: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

ForcesForces

A description of system constraints. A description of system constraints. A good design pattern resolves these A good design pattern resolves these

forces as far as possible. forces as far as possible. The forces themselves are often in conflict The forces themselves are often in conflict

and will need to be balanced in the final and will need to be balanced in the final design. design.

This may result in trade offs among This may result in trade offs among system objectives, criteria, and resources. system objectives, criteria, and resources.

Page 20: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Types of forcesTypes of forces

Resource forces (e.g., time vs. space) Resource forces (e.g., time vs. space) Structural forces (e.g., reusability, Structural forces (e.g., reusability,

modularity, extensibility) modularity, extensibility) Strategic forces (e.g., relationships to Strategic forces (e.g., relationships to

other software, maintenance issues) other software, maintenance issues) System integrity forces (e.g., correctness, System integrity forces (e.g., correctness,

security, fault tolerance) security, fault tolerance) Human factor forces (e.g., aesthetics, Human factor forces (e.g., aesthetics,

learning curve, social impact) learning curve, social impact)

Page 21: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Sample QuestionsSample Questions

What forces constrain a word processor What forces constrain a word processor when opening a document?when opening a document?

What forces affect how a Web browser What forces affect how a Web browser loads a Web page?loads a Web page?

What are the most significant forces What are the most significant forces affecting a context-sensitive help system?affecting a context-sensitive help system?

Page 22: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

The problem of handling different The problem of handling different document types in an application can be document types in an application can be resolved by having the application hold a resolved by having the application hold a reference to an abstract document type. reference to an abstract document type.

Page 23: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Upon loading a document, that reference Upon loading a document, that reference gets resolved to a concrete document type gets resolved to a concrete document type (which is a subtype of the abstract (which is a subtype of the abstract document class) or else the application document class) or else the application displays a message such as "Document displays a message such as "Document type not recognized".type not recognized".

This solution employs the Template This solution employs the Template Method pattern.Method pattern.

Page 24: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

SolutionSolution

The resolution of the forces in the The resolution of the forces in the problem. problem.

A pattern is not simply a strategy, A pattern is not simply a strategy, algorithm, or heuristic. algorithm, or heuristic.

Patterns are generative. Patterns are generative. Patterns describe the creation of an object Patterns describe the creation of an object

whose possession resolves the given whose possession resolves the given forces. forces.

Page 25: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Patterns start with observation, not with Patterns start with observation, not with theory. theory.

One could argue that patterns are by One could argue that patterns are by nature metaphorical. nature metaphorical.

The best patterns solve problems by The best patterns solve problems by simply giving us a way of thinking about simply giving us a way of thinking about the problem. the problem.

Page 26: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

A specific pattern frequently found in GUI A specific pattern frequently found in GUI design is called Composite, which allows design is called Composite, which allows aggregate objects to be viewed as a tree aggregate objects to be viewed as a tree hierarchy. hierarchy.

The Composite pattern works by creating The Composite pattern works by creating a hierarchy for which some subobjects are a hierarchy for which some subobjects are atomic and other subobjects are atomic and other subobjects are themselves composite (hence giving a themselves composite (hence giving a recursive structure to the hierarchy). recursive structure to the hierarchy).

Page 27: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

At the root is the entire object, each node At the root is the entire object, each node is a subobject. An atomic object will is a subobject. An atomic object will appear as a leaf in the hierarchy. This appear as a leaf in the hierarchy. This allows the designer to easily create nested allows the designer to easily create nested visual objects (i.e., objects which are visual objects (i.e., objects which are composed of other visual objects). composed of other visual objects).

Page 28: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

ExamplesExamples

Also called Known UsesAlso called Known Uses Specific applications of the pattern. Specific applications of the pattern. This may include sample code and uses of This may include sample code and uses of

the pattern in existing systems. the pattern in existing systems.

Page 29: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Resulting ContextResulting Context

The consequences of applying the pattern. The consequences of applying the pattern. This gives the new state of the system, This gives the new state of the system,

including the resolution of the forces in the including the resolution of the forces in the initial context. initial context.

Page 30: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

RationaleRationale

A justification for the pattern. That is, it A justification for the pattern. That is, it explains why the pattern works. explains why the pattern works.

Page 31: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Types of PatternsTypes of Patterns

Patterns occur at different granularities. Patterns occur at different granularities. That is, patterns can be found in structures That is, patterns can be found in structures

ranging from entire organizations through ranging from entire organizations through large-scale software applications down to large-scale software applications down to individual objects and program fragments. individual objects and program fragments.

Page 32: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Primary pattern types Primary pattern types

ArchitecturalArchitectural DesignDesign IdiomsIdioms ProgrammingProgramming Organizational Organizational

Page 33: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Architectural PatternsArchitectural Patterns

Architectural patterns describe system Architectural patterns describe system structure. structure.

These patterns specify the components of These patterns specify the components of a system, their responsibilities, and a system, their responsibilities, and relationships.relationships.

Page 34: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

A well-known example of an architectural A well-known example of an architectural pattern is the Model-View-Controller pattern is the Model-View-Controller (MVC) pattern used to build interactive (MVC) pattern used to build interactive applications. applications.

The MVC pattern solves the problem of The MVC pattern solves the problem of separating the application core from its separating the application core from its presentation. presentation.

Page 35: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

The Model contains the underlying data The Model contains the underlying data and functionality of the application. and functionality of the application.

The View defines the visual display. The View defines the visual display. The Controller handles user input.The Controller handles user input.

Page 36: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

MVC PatternMVC Pattern

Pattern:Pattern: Model-View-Controller (MVC) Model-View-Controller (MVC) Problem:Problem: How to coordinate data How to coordinate data

handling, presentation, and user input in handling, presentation, and user input in an interactive application.an interactive application.

Context:Context: Interactive, event-driven Interactive, event-driven applications that couple the data model applications that couple the data model and view are difficult to adapt and modify. and view are difficult to adapt and modify.

Page 37: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Forces:Forces: The application core should be The application core should be independent of its presentation. This core independent of its presentation. This core should be reusable. The application should be reusable. The application should support different simultaneous should support different simultaneous views of the data. Adding new views or views of the data. Adding new views or new input handling should be new input handling should be straightforward. All views must be notified straightforward. All views must be notified when data changes.when data changes.

Page 38: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Solution:Solution: Decouple the data handling Decouple the data handling (Model), the data presentation (View) and (Model), the data presentation (View) and the user input handling (Controller). Make the user input handling (Controller). Make each component a full-fledged object. The each component a full-fledged object. The Model maintains a list of its Views (a View Model maintains a list of its Views (a View can subscribe/unsubscribe to a Model at can subscribe/unsubscribe to a Model at run-time). Each View has an associated run-time). Each View has an associated Controller. When the Model is modified it Controller. When the Model is modified it then notifies each View (this is known as then notifies each View (this is known as the Notify/Subscribe pattern).the Notify/Subscribe pattern).

Page 39: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Sample CodeSample Code

class Model;class Model;

class View { //Shown as an abstract base classclass View { //Shown as an abstract base class

protected:protected:

View();View();

public:public:

virtual void Update(Model virtual void Update(Model *theChangedModel) = 0; *theChangedModel) = 0;

};};

Page 40: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

class Model { //Concrete, but polymorphicprivate:

List<View*> *_models;protected:

Model();public:

void Subscribe(View *v) { _models->insert(v); }void Unsubscribe(View *v) {

_models->remove(v); }virtual void Notify() {

List<View*>::iterator start, stop;start = _models->begin();stop = _models->end();for( ; start != stop; ++start)

(*start).Update(this);}

};

Page 41: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns
Page 42: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns
Page 43: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

ExamplesExamples

This is a basic pattern of user interface This is a basic pattern of user interface design. design.

The Smalltalk user-interface framework is The Smalltalk user-interface framework is based on the MVC pattern. based on the MVC pattern.

The Microsoft Foundation Class (MFC) The Microsoft Foundation Class (MFC) library is also based on the MVC pattern. library is also based on the MVC pattern.

Page 44: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Resulting ContextResulting Context

The Model has no specific knowledge of The Model has no specific knowledge of the possible Views. the possible Views.

The Model and View can belong to The Model and View can belong to different levels of the system. different levels of the system.

The View objects handle notification of The View objects handle notification of changes in data in their own way (i.e., changes in data in their own way (i.e., each View is a subclass of the abstract each View is a subclass of the abstract base class). base class).

Page 45: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

RationaleRationale

This pattern supports multiple views for a This pattern supports multiple views for a model. model.

For example, data in a spreadsheet can For example, data in a spreadsheet can be presented as a table or as a chart. be presented as a table or as a chart.

Different views for the model can be Different views for the model can be written without changing the model. written without changing the model.

This kind of flexibility is a key to object-This kind of flexibility is a key to object-oriented programming. oriented programming.

Page 46: C++ Training Datascope Lawrence D’Antonio Lecture 12 Design Patterns

Design PatternsDesign Patterns

Design patterns describe subsystem Design patterns describe subsystem structure. structure.

Design patterns focus on particular design Design patterns focus on particular design problems. problems.

There are three categories of design There are three categories of design patterns: creational, structural, and patterns: creational, structural, and behavioral.behavioral.