COMP 345 Advanced Program Design with C 1

  • Slides: 79
Download presentation
COMP 345 - Advanced Program Design with C++ 1 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 1 Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Design patterns Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 2 Design patterns • “Each pattern

COMP 345 - Advanced Program Design with C++ 2 Design patterns • “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 the same way twice. ” [Christopher Alexander – late 1970 s] • A Pattern Language (1977) • A Timeless Way of Building (1979) • Design patterns capture the best practices of experienced object- oriented software developers. • Design patterns are solutions to general software development problems. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 3 Pattern elements • In general,

COMP 345 - Advanced Program Design with C++ 3 Pattern elements • In general, a pattern has four essential elements. • The pattern name • The problem • The solution • The consequences Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 4 Pattern elements: name • The

COMP 345 - Advanced Program Design with C++ 4 Pattern elements: name • The pattern name is a handle we can use to describe a design problem, its solutions, and consequences in a word or two. • Naming a pattern immediately increases the design vocabulary. It lets us design at a higher level of abstraction. • Having a vocabulary for patterns lets us talk about them. • It makes it easier to think about designs and to communicate them and their trade-offs to others. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 5 Pattern elements: problem • The

COMP 345 - Advanced Program Design with C++ 5 Pattern elements: problem • The problem describes when to apply the pattern. • It explains the problem and its context. • It might describe specific design problems such as how to represent algorithms as objects. • It might describe class or object structures that are symptomatic of an inflexible design. • Sometimes the problem will include a list of conditions that must be met before it makes sense to apply the pattern. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 6 Pattern elements: solution • The

COMP 345 - Advanced Program Design with C++ 6 Pattern elements: solution • The solution describes the elements that make up the design, their relationships, responsibilities, and collaborations. • The solution doesn't describe a particular concrete design or implementation, because a pattern is like a template that can be applied in many different situations. • Instead, the pattern provides an abstract description of a design problem and how a general arrangement of elements (classes and objects in our case) solves it. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 7 Pattern elements: consequences • The

COMP 345 - Advanced Program Design with C++ 7 Pattern elements: consequences • The consequences are the results and trade-offs of applying the pattern. • The consequences for software often concern space and time trade-offs. • They may address language and implementation issues as well. • Since reuse is often a factor in object-oriented design, the consequences of a pattern include its impact on a system's flexibility, extensibility, or portability. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 8 Design pattern: types • Erich

COMP 345 - Advanced Program Design with C++ 8 Design pattern: types • Erich Gamma, Richard Helm, Ralph Johnson and John Vlisides in their Design Patterns [gang of four ] book define 23 design patterns divided into three types: • Creational patterns - create objects for you, rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case. • Structural patterns - help you compose groups of objects into larger structures, such as complex user interfaces or accounting data. • Behavioral patterns - help you define the communication between objects in your system and how the flow is controlled in a complex program. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 9 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 9 Click to edit Master title style Creational patterns Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 10 Creational patterns: concept • The

COMP 345 - Advanced Program Design with C++ 10 Creational patterns: concept • The creational patterns deal with the best way to create instances of objects. • In C++, the simplest ways to create an instance of an object is by using the new operator or by simply declaring the variable in the local scope: Fred* fred 1 = new Fred(); //instance of Fred class Fred fred 2; //instance of Fred class • The amount of hard coding depends on how you create the object within your program. • In many cases, the exact nature of the object that is created could vary with the needs of the program and abstracting the creation process into a special “creator” class can make your program more flexible and general. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 11 Creational patterns: examples • The

COMP 345 - Advanced Program Design with C++ 11 Creational patterns: examples • The Factory Pattern provides a simple decision making class that returns one of several possible subclasses of an abstract base class depending on the data that are provided. • The Abstract Factory Pattern provides an interface to create and return one of several families of related objects. • The Builder Pattern separates the construction of a complex object from its representation. • The Prototype Pattern starts with an initialized and instantiated class and copies or clones it to make new instances rather than creating new instances. • The Singleton Pattern is a class of which there can be no more than one instance. It provides a single global point of access to that instance. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 12 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 12 Click to edit Master title style Factory pattern Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 13 Factory pattern • The Factory

COMP 345 - Advanced Program Design with C++ 13 Factory pattern • The Factory pattern returns an instance of one of several possible classes depending on the data provided to it. • Here, x is a base class and classes xy and xz are derived from it. • The Factory is a class that decides which of these subclasses to return depending on the arguments you give it. • The get. Class() method passes in some value abc, and returns some instance of one of the subclasses of the class x. Which one it returns doesn't matter to the programmer since they all have the same methods, but different implementations. • This is supposing that the object produced will be used polymorphically. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 14 Factory pattern: example class Shape.

COMP 345 - Advanced Program Design with C++ 14 Factory pattern: example class Shape. Factory { public: // Static method to create objects // Change is required only in this function to create a new object type static Shape* Create(string type){ if ( type == "circle" ) return new Circle(); if ( type == "square" ) return new Square(); return NULL; } private: Shape. Factory(){}; }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 15 Factory pattern: example class Shape

COMP 345 - Advanced Program Design with C++ 15 Factory pattern: example class Shape { public: virtual void draw() = 0; }; class Square : public Shape { public: void draw() { cout << "I am square" << endl; } }; class Circle : public Shape { public: void draw() { cout << "I am circle" << endl; } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 16 Factory pattern: example int main()

COMP 345 - Advanced Program Design with C++ 16 Factory pattern: example int main() { // Give me a circle Shape* shape 1 = Shape. Factory: : Create("circle"); // Give me a square Shape* shape 2 = Shape. Factory: : Create("square"); shape 1 ->draw(); // will call appropriate draw() shape 2 ->draw(); // as it is defined as virtual delete shape 1; delete shape 2; system("PAUSE"); } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 17 Factory pattern: context • You

COMP 345 - Advanced Program Design with C++ 17 Factory pattern: context • You should consider using a Factory pattern when: • Various kinds of objects are to be used polymorphically. • A class uses a hierarchy of classes to specify which objects it creates. • A class can’t anticipate the kind of objects it must create. • You want to localize the knowledge of which class gets created. • How to recognize variations of the Factory pattern? • The base class is (most often) abstract. • The base class contains default methods and is only subclassed for cases where the default methods are insufficient. • Parameters are passed to the factory telling it which of several class types to return. • Classes may share the same method names but may do something quite different. • Also often called a “factory method”. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 18 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 18 Click to edit Master title style Abstract factory pattern Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 19 Abstract factory • The Abstract

COMP 345 - Advanced Program Design with C++ 19 Abstract factory • The Abstract Factory pattern is one level of abstraction higher than the factory pattern. • This pattern returns one of several related classes, each of which can return several different objects on request. In other words, the Abstract Factory is a factory object that returns one of several factories. • One classic application of the abstract factory is the case where your system needs to support multiple “look-and-feel” user interfaces, such as Windows, Linux or Macintosh: • You tell the factory that you want your program to look like Windows and it returns a GUI factory which returns Windows-like objects. • When you request specific objects such as buttons, check boxes and windows, the GUI factory returns Windows instances of these visual interface components. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 20 Abstract factory: example class Widget

COMP 345 - Advanced Program Design with C++ 20 Abstract factory: example class Widget { public: virtual void draw() = 0; }; class Widget. Factory { public: virtual Widget* create_button() = 0; virtual Widget* create_menu() = 0; }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 21 Abstract factory: example class Motif.

COMP 345 - Advanced Program Design with C++ 21 Abstract factory: example class Motif. Widget. Factory : public Widget. Factory { public: Widget* create_button() { return new Motif. Button; } Widget* create_menu() { return new Motif. Menu; } }; class Motif. Button : public Widget { public: void draw() { cout << "Motif. Buttonn"; } }; class Motif. Menu : public Widget { public: void draw() { cout << "Motif. Menun"; } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 22 Abstract factory: example class Windows.

COMP 345 - Advanced Program Design with C++ 22 Abstract factory: example class Windows. Widget. Factory : public Widget. Factory { public: Widget* create_button() { return new Windows. Button; } Widget* create_menu() { return new Windows. Menu; } }; class Windows. Button : public Widget { public: void draw() { cout << "Windows. Buttonn"; } }; class Windows. Menu : public Widget { public: void draw() { cout << "Windows. Menun"; } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 23 Abstract factory: example //uncomment the

COMP 345 - Advanced Program Design with C++ 23 Abstract factory: example //uncomment the following to generate Motif widgets //#define MOTIF //uncomment the following to generate Windows widgets #define WINDOWS int main(int argc, char *argv[]) { Widget. Factory *widget_factory; #ifdef MOTIF widget_factory = new Motif. Widget. Factory; #else // WINDOWS widget_factory = new Windows. Widget. Factory; #endif Widget* w[2] = {widget_factory->create_button(), widget_factory->create_menu()}; w[0]->draw(); w[1]->draw(); system("PAUSE"); return EXIT_SUCCESS; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 24 Abstract factory: consequences • One

COMP 345 - Advanced Program Design with C++ 24 Abstract factory: consequences • One of the main purposes of the Abstract Factory is that it abstracts the concrete classes from which the objects are instantiated. • The actual class names of these classes are hidden in the factory and need not be known at the client level at all. • Because of the isolation of classes, you can change or interchange these product class families freely. • Since you generate only one kind of concrete class, this system keeps you for inadvertently using classes from different families of products. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 25 Abstract factory: consequences • Requires

COMP 345 - Advanced Program Design with C++ 25 Abstract factory: consequences • Requires the use of polymorphic design. • While all of the classes that the Abstract Factory generates have the same base class, there is nothing to prevent some derived classes from having additional methods that differ from the methods of other classes. • This may lead to more complex use though. • Often used in conjunction with the adapter pattern to have similar classes to expose the same interface. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 26 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 26 Click to edit Master title style Builder pattern Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 27 Builder pattern • The Builder

COMP 345 - Advanced Program Design with C++ 27 Builder pattern • The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. • Builder - specifies an abstract interface for creating parts of a Product object. • Concrete. Builder - constructs and assembles parts of the product by implementing the Builder interface. Also, it defines and keeps track of the representation it creates and provides an interface for retrieving the product. • Director - constructs an object using the Builder interface. • Product - represents the complex object under construction. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 28 Builder pattern • The following

COMP 345 - Advanced Program Design with C++ 28 Builder pattern • The following interaction diagram illustrates how Builder and Director cooperate with a client. • The client creates the Director object and configures it with the desired Builder object. • Director notifies the builder whenever a part of the product should be built. • Builder handles requests from the director and adds parts to the product. • The client retrieves the product from the builder. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 29 Builder pattern: example //Superclass of

COMP 345 - Advanced Program Design with C++ 29 Builder pattern: example //Superclass of all kinds of objects to be created //Generically called “Product” class Pizza { public: //Set all parts of the Product, and use the Product void set. Dough(const string& dough){ m_dough = dough; } void set. Sauce(const string& sauce){ m_sauce = sauce; } void set. Topping(const string& topping){ m_topping = topping; } void open() const{ cout << "Pizza with " << m_dough << " dough, " << m_sauce << " sauce and " << m_topping << " topping. Mmm. " << endl; } private: //Parts of the Product string m_dough; string m_sauce; string m_topping; }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 30 Builder pattern: example // Abstract

COMP 345 - Advanced Program Design with C++ 30 Builder pattern: example // Abstract class providing the structure for all // concrete pizza builders class Pizza. Builder { public: //get the built Pizza from the Builder Pizza* get. Pizza(){ return m_pizza; } //build a generic empty Pizza void create. New. Pizza. Product(){ m_pizza = new Pizza; } //create each part of the Product according to subtypes virtual void build. Dough() = 0; virtual void build. Sauce() = 0; virtual void build. Topping() = 0; protected: //Product built by Pizza Builder Pizza* m_pizza; }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 31 Builder pattern: example class Hawaiian.

COMP 345 - Advanced Program Design with C++ 31 Builder pattern: example class Hawaiian. Pizza. Builder : public Pizza. Builder //Concrete Builder 1 { public: virtual void build. Dough() //Build different parts of the pizza {m_pizza->set. Dough("cross"); } //The construction process could be virtual void build. Sauce() //more complex in a real-life example {m_pizza->set. Sauce("mild"); } //The construction of the pizza part virtual void build. Topping() //depends on the type of pizza. {m_pizza->set. Topping("ham+pineapple"); } }; class Spicy. Pizza. Builder : public Pizza. Builder //Concrete Builder 2 { public: virtual void build. Dough() //The construction process may vary {m_pizza->set. Dough("pan baked"); } //across different Concrete Builders. virtual void build. Sauce() {m_pizza->set. Sauce("hot"); } virtual void build. Topping() {m_pizza->set. Topping("pepperoni+salami"); } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 32 Builder pattern: example class Cook

COMP 345 - Advanced Program Design with C++ 32 Builder pattern: example class Cook //Director { public: void set. Pizza. Builder(Pizza. Builder* pb) //Use a concrete builder { //for building a specific m_pizza. Builder = pb; //kind of Pizza. } Pizza* get. Pizza() //get the constructed Pizza { return m_pizza. Builder->get. Pizza(); } void construct. Pizza() //Creational process to create { //a pizza using the builder. m_pizza. Builder->create. New. Pizza. Product(); m_pizza. Builder->build. Dough(); m_pizza. Builder->build. Sauce(); m_pizza. Builder->build. Topping(); } private: Pizza. Builder* m_pizza. Builder; }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 33 Builder pattern: example //Pizza Builder

COMP 345 - Advanced Program Design with C++ 33 Builder pattern: example //Pizza Builder Client int main() { Cook cook; //Create the Director Pizza. Builder* hawaiian. Pizza. Builder = //Create the Concrete Builder new Hawaiian. Pizza. Builder; Pizza. Builder* spicy. Pizza. Builder = new Spicy. Pizza. Builder; cook. set. Pizza. Builder(hawaiian. Pizza. Builder); //Tell the Director which Builder to use cook. construct. Pizza(); //Tell the Director to construct the Product Pizza* hawaiian = cook. get. Pizza(); //Client gets the Product hawaiian->open(); //Client uses the Product cook. set. Pizza. Builder(spicy. Pizza. Builder); //same for another kind of product cook. construct. Pizza(); Pizza* spicy = cook. get. Pizza(); spicy->open(); delete hawaiian. Pizza. Builder; delete spicy. Pizza. Builder; delete hawaiian; delete spicy; system("PAUSE"); return EXIT_SUCCESS; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 34 Builder pattern: context • Use

COMP 345 - Advanced Program Design with C++ 34 Builder pattern: context • Use the Builder pattern when: • The algorithm for creating a complex object should be independent of the parts that make up the object and how they are assembled. • The construction process must allow different representations for the object that is constructed. • Complex objects need to be created that have a common overall structure and interface, even though their internal behavior and detailed structure may be different. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 35 Builder pattern: consequences • A

COMP 345 - Advanced Program Design with C++ 35 Builder pattern: consequences • A Builder lets you vary the internal representation of the product it builds. It also hides the details of how the product is assembled. It provides construction abstraction. • Each specific builder is independent of the others and of the rest of the program. This improves modularity and makes the addition of other builders relatively simple. • Because each builder constructs the final product step-by-step, you have more control over each final product that a Builder constructs. • A Builder pattern is somewhat like an Abstract Factory pattern in that both return classes made up of a number of methods and objects. The main difference is that while the Abstract Factory returns a family of related classes, the Builder constructs a complex object step by step depending on the data presented to it. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 36 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 36 Click to edit Master title style Singleton pattern Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 37 Singleton pattern • Sometimes it

COMP 345 - Advanced Program Design with C++ 37 Singleton pattern • Sometimes it is appropriate to have exactly one instance of a class: • window managers, • print spoolers, • filesystems. • Typically, those types of objects known as singletons, are accessed by disparate objects throughout a software system, and therefore require a global point of access. • The Singleton pattern addresses all the concerns above. With the Singleton design pattern you can: • Ensure that only one instance of a class is created. • Provide a global point of access to the object. • Allow multiple instances in the future without affecting a singleton class' clients. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 38 Singleton pattern • The Singleton

COMP 345 - Advanced Program Design with C++ 38 Singleton pattern • The Singleton pattern ensures a class has only one instance, and provides a global point of access to it. • The class itself is responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. • Singletons maintain a static reference to the sole singleton instance and return a reference to that instance from a static instance() method. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 39 Singleton: example class Singleton. Class

COMP 345 - Advanced Program Design with C++ 39 Singleton: example class Singleton. Class { private: int m_value; static Singleton. Class *s_instance; Singleton. Class() { m_value = 0; } public: int get_value() { return m_value; } void increment_value() { m_value++; } static Singleton. Class *instance() { if (!s_instance) s_instance = new Singleton. Class(); return s_instance; } }; // Allocating and initializing Singleton. Class's // static data member. The pointer is being // allocated - not the object itself. Singleton. Class *Singleton. Class: : s_instance = 0; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 40 Singleton: example void foo(void) {

COMP 345 - Advanced Program Design with C++ 40 Singleton: example void foo(void) { Singleton. Class: : instance()->increment_value(); cout << "foo: global_ptr is " << Singleton. Class: : instance()->get_value() << 'n'; } void bar(void) { Singleton. Class: : instance()->increment_value(); cout << "bar: global_ptr is " << Singleton. Class: : instance()->get_value() << 'n'; } int main(int argc, char *argv[]) { cout << "main: global_ptr is " << Singleton. Class: : instance()->get_value() << 'n'; foo(); bar(); //Singleton. Class s = new Singleton. Class(); system("PAUSE"); return EXIT_SUCCESS; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 41 Singleton • The Singleton class

COMP 345 - Advanced Program Design with C++ 41 Singleton • The Singleton class employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the Instance() method is called for the first time. This technique ensures that the singleton instance iscreated only when needed. • The Singleton class implements a protected constructor so clients cannot instantiate Singleton instances. • Protected constructors allow Singleton subclasses to be created. • Even though the Singleton is an interesting pattern, it is essentially a global variable, and as such should be used with caution. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 42 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 42 Click to edit Master title style Structural patterns Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 43 Structural patterns • Structural patterns

COMP 345 - Advanced Program Design with C++ 43 Structural patterns • Structural patterns describe how classes and objects can be combined to form larger structures. • The difference between class patterns and object patterns is that class patterns describe how inheritance can be used to provide more useful program interfaces. • Object patterns, on the other hand, describe how objects can be composed into larger structures using object composition, or the inclusion of objects within other objects. • Some of the Structural patterns are: • Adapter • Composite • Façade • Bridge • Decorator Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 44 Structural patterns • The Flyweight

COMP 345 - Advanced Program Design with C++ 44 Structural patterns • The Flyweight pattern is a pattern for sharing objects, where each instance does not contain its own state, but stores it externally. This allows efficient sharing of objects to save space, when there are many instances, but only a few different types. • The Façade pattern is used to make a single class represent an entire subsystem. • The Bridge pattern separates an object’s interface from its implementation, so you can vary them separately. • The Decorator pattern can be used to add responsibilities to objects dynamically. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 45 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 45 Click to edit Master title style Adapter pattern Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 46 Adapter pattern • Motivation •

COMP 345 - Advanced Program Design with C++ 46 Adapter pattern • Motivation • Like any adapter in the real world it is used to be an interface, a bridge between two objects that have the same functionality, but that are to be used in a different manner, i. e. have a different specification to their interfaces. In real world we have adapters for power supplies, adapters for camera memory cards, and so on. • The same concept applies to software components. You may have some class expecting some type of object and you have an object offering the same features, but exposing a different interface. You don't want to change existing classes, so you want to create an adapter. • Intent • Convert the interface of a class into another interface that clients expect. • Adapter lets classes work together, that could not otherwise because of incompatible interfaces. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 47 Adapter pattern: structure • The

COMP 345 - Advanced Program Design with C++ 47 Adapter pattern: structure • The classes/objects participating in adapter pattern: • Target - defines the domain-specific interface that Client uses. • Adapter - adapts the interface Adaptee to the Target interface. • Adaptee - defines an existing interface that needs adapting. • Client - collaborates with objects conforming to the Target interface. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 48 Adapter pattern • The adapter

COMP 345 - Advanced Program Design with C++ 48 Adapter pattern • The adapter pattern is used: • When you have a class (Target) that invokes methods defined in an interface and you have a another class (Adaptee) that doesn't implement the interface but implements the operations that should be invoked from the first class through the interface. • You can change none of the existing code. • You need an adapter to implement the interface that will be the bridge between the two classes. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 49 Adapter pattern: example • If

COMP 345 - Advanced Program Design with C++ 49 Adapter pattern: example • If a client only understands the Square. Peg interface for inserting pegs using the insert. Into. Square. Hole() method, how can it insert round pegs, which are pegs, but that are inserted differently, using the insert. Into. Round. Hole() method? /** * The Round. Peg class. * This is the Adaptee class. */ class Round. Peg { public: void insert. Into. Round. Hole(string str) { cout << "Round. Peg insert. Into. Round. Hole(): " << str; } }; /** * The Square. Peg class. * This is the Target class. */ class Square. Peg { public: void insert. Into. Square. Hole(string str){ cout << "Square. Peg insert. Into. Square. Hole(): " << str; } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 50 Adapter pattern: example • Solution:

COMP 345 - Advanced Program Design with C++ 50 Adapter pattern: example • Solution: • Design a Square. To. Round. Peg. Adapter that enables to insert. Into. Round. Hole() a Round. Peg object connected to the adapter to be inserted as a Square. Peg, using insert. Into. Square. Hole(). /** * The Square. To. Round. Peg. Adapter class. * This is the Adapter class. * It adapts a Square. Peg to a Round. Peg. * Its interface is that of a Square. Peg. */ class Square. To. Round. Peg. Adapter: public Square. Peg { private: Round. Peg round. Peg; public: Square. To. Round. Peg. Adapter(Round. Peg peg) { //the round. Peg is plugged into the adapter round. Peg = peg; } void insert. Into. Square. Hole(string str) { //the round. Peg can now be inserted in the same manner as a square. Peg! round. Peg. insert. Into. Round. Hole(str); } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 51 Adapter pattern: example int main(int

COMP 345 - Advanced Program Design with C++ 51 Adapter pattern: example int main(int argc, char *argv[]) { // Create some pegs. Round. Peg *round. Peg = new Round. Peg(); Square. Peg *square. Peg = new Square. Peg(); // Do an insert using the square peg. square. Peg->insert. Into. Square. Hole( "Inserting square peg. . . n"); // Now we'd like to do an insert using the round peg. // But this client only understands the insert() // method of pegs, not a insert. Into. Hole() method. // The solution: create an adapter that adapts // a square peg to a round peg! Square. To. Round. Peg. Adapter *adapter = new Square. To. Round. Peg. Adapter(*round. Peg); adapter->insert. Into. Square. Hole( "Inserting round peg. . . n"); Square. Peg *sq_pegs[2] = {new Square. Peg(), new Square. To. Round. Peg. Adapter(*round. Peg)}; sq_pegs[0]->insert. Into. Square. Hole( "Inserting square peg [0]. . . n"); sq_pegs[1]->insert. Into. Square. Hole( "Inserting square peg [1]. . . n"); system("PAUSE"); return EXIT_SUCCESS; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 52 Two way adapter pattern: example

COMP 345 - Advanced Program Design with C++ 52 Two way adapter pattern: example • Two-way adapter. • Multiple inheritance. class Square. Peg { public: virtual void insert. Square. Peg(string str) { cout << "Square. Peg insert. Square. Peg(): " << str; } }; class Round. Peg { public: virtual void insert. Round. Peg(string str) { cout << "Round. Peg insert. Round. Peg(): " << str; } }; class Two. Way. Peg. Adapter: public Square. Peg, public Round. Peg { private: Round. Peg *round. Peg; Square. Peg *square. Peg; public: Two. Way. Peg. Adapter(Round. Peg *peg) { //a round. Peg is plugged into the adapter round. Peg = peg; square. Peg = NULL; } Two. Way. Peg. Adapter(Square. Peg *peg) { //a square. Peg is plugged into the adapter square. Peg = peg; round. Peg = NULL; } void insert. Round. Peg(string str) { square. Peg->insert. Square. Peg( str); } void insert. Square. Peg(string str) { round. Peg->insert. Round. Peg(str); } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 53 Two way adapter pattern: example

COMP 345 - Advanced Program Design with C++ 53 Two way adapter pattern: example int main(int argc, char *argv[]) { Round. Peg *round. Peg = new Round. Peg(); Square. Peg *square. Peg = new Square. Peg(); Square. Peg *square. Peg. Array[2] = {square. Peg, new Two. Way. Peg. Adapter(round. Peg)}; square. Peg. Array[0]->insert. Square. Peg( "Inserting Square Peg in square. Peg. Array[0]. . . n" ); square. Peg. Array[1]->insert. Square. Peg( "Inserting Square Peg in square. Peg. Array[1]. . . n" ); Round. Peg *round. Peg. Array[2] = {round. Peg, new Two. Way. Peg. Adapter(square. Peg)}; round. Peg. Array[0]->insert. Round. Peg( "Inserting Round Peg in round. Peg. Array[0]. . . n" ); round. Peg. Array[1]->insert. Round. Peg( "Inserting Round Peg in round. Peg. Array[1]. . . n" ); system("PAUSE"); return EXIT_SUCCESS; }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 54 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 54 Click to edit Master title style Decorator pattern Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 55 Decorator pattern • Motivation: •

COMP 345 - Advanced Program Design with C++ 55 Decorator pattern • Motivation: • Sometimes we may want to dynamically add some data members or methods to an object at runtime, depending on the situation. • Intent: • Allow to add new functionality to an existing object without altering its structure. • Create a Decorator class that wraps the original class. • Provides additional functionality while keeping the class’ methods’ signatures intact. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 56 Decorator pattern • Elements of

COMP 345 - Advanced Program Design with C++ 56 Decorator pattern • Elements of the Decorator pattern: • Component: Abstract class representing the objects to be decorated by the various Decorators. • Concrete Component: The potentially many sub-classes that can be decorated. • Decorator: Abstract class that wraps a Component and will have some of its subclasses to decorate it. • Concrete Decorator: Different decorators that add different members to the Component. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 57 Decorator pattern: example /** *

COMP 345 - Advanced Program Design with C++ 57 Decorator pattern: example /** * The abstract Coffee class defines the functionality of any Coffee * implemented by subclasses of Coffee */ class Coffee { public: virtual double get. Cost() = 0; virtual string get. Ingredients() = 0; }; /** * Kind of Coffee */ class Espresso : public Coffee { public: double get. Cost(){ return 1. 25; } string get. Ingredients(){ return "Strong Coffee"; } }; Concordia University /** * Kind of Coffee */ class Simple. Coffee : public Coffee { public: double get. Cost(){ return 1; } string get. Ingredients(){ return "Coffee"; } }; Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 58 Decorator pattern: example /** *

COMP 345 - Advanced Program Design with C++ 58 Decorator pattern: example /** * Abstract decorator class - note that it extends the Coffee abstract class */ class Coffee. Decorator : public Coffee { protected: Coffee *decorated. Coffee; public: /** * Wraps a Coffee object inside an object of one of * Coffee. Decorator's subclasses */ Coffee. Decorator(Coffee *decorated. Coffee){ this->decorated. Coffee = decorated. Coffee; } /** * Provides the wrapper with the Coffee interface and delegates * its methods to the wrapped Coffee object. */ double get. Cost(){ return decorated. Coffee->get. Cost(); } string get. Ingredients(){ return decorated. Coffee->get. Ingredients(); } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 59 Decorator pattern: example /** Decorator

COMP 345 - Advanced Program Design with C++ 59 Decorator pattern: example /** Decorator that mixes Milk with coffee. * It is a subclass of Coffee. Decorator, and thus a subclass of Coffee. */ class Milk : public Coffee. Decorator { public: /** * When creating a decorated Coffee, pass a Coffee to be decorated * as a parameter. Note that this can be an already-decorated Coffee. */ Milk(Coffee *decorated. Coffee) : Coffee. Decorator(decorated. Coffee){} /** * Overriding methods defined in the abstract superclass. * Enables to provide different behavior for decorated Coffee methods */ double get. Cost(){ return Coffee. Decorator: : get. Cost() + 0. 5; } string get. Ingredients(){ return Coffee. Decorator: : get. Ingredients() + ", Milk"; } /** * May also additional members for decorated-specific data * or behavior */ }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 60 Decorator pattern: example class Sprinkles

COMP 345 - Advanced Program Design with C++ 60 Decorator pattern: example class Sprinkles : public Coffee. Decorator { public: Sprinkles(Coffee *decorated. Coffee) : Coffee. Decorator(decorated. Coffee){} double get. Cost(){ return Coffee. Decorator: : get. Cost() + 0. 2; } string get. Ingredients(){ return Coffee. Decorator: : get. Ingredients() + ", Sprinkles"; } }; class Whip : public Coffee. Decorator { public: Whip(Coffee *decorated. Coffee) : Coffee. Decorator(decorated. Coffee){} double get. Cost(){ return Coffee. Decorator: : get. Cost() + 0. 2; } string get. Ingredients(){ return Coffee. Decorator: : get. Ingredients() + ", Sprinkles"; } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 61 Decorator pattern: example int main(){

COMP 345 - Advanced Program Design with C++ 61 Decorator pattern: example int main(){ Coffee *c = new Simple. Coffee(); cout << "Cost: " << c->get. Cost() << “ Ingredients: " << c->get. Ingredients() << endl; c = new Milk(c); cout << "Cost: " << c->get. Cost() << “ Ingredients: " << c->get. Ingredients() << endl; c = new Sprinkles(c); cout << "Cost: " << c->get. Cost() << “ Ingredients: " << c->get. Ingredients() << endl; c = new Whip(c); cout << "Cost: " << c->get. Cost() << “ Ingredients: " << c->get. Ingredients() << endl; // Note that you can also stack more than one decorator of the same type c = new Sprinkles(c); cout << "Cost: " << c->get. Cost() << “ Ingredients: " << c->get. Ingredients() << endl; c = new Espresso(); cout << "Cost: " << c->get. Cost() << “ Ingredients: " << c->get. Ingredients() << endl; c = new Milk(c); cout << "Cost: " << c->get. Cost() << “ Ingredients: " << c->get. Ingredients() << endl; system("PAUSE"); return EXIT_SUCCESS; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 62 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 62 Click to edit Master title style Behavioral patterns Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 63 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 63 Click to edit Master title style Observer pattern Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 64 Observer pattern: motivation, intent •

COMP 345 - Advanced Program Design with C++ 64 Observer pattern: motivation, intent • Motivation • The cases when certain objects need to be informed about the changes occurring in other objects are frequent. To have a good design means to decouple as much as possible and to reduce the dependencies. The Observer Design Pattern can be used whenever a subject has to be observed by one or more observers. • Intent • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. • This pattern is a cornerstone of the Model-View-Controller architectural design, where the Model implements the mechanics of the program, and the Views are implemented as Observers that are as much uncoupled as possible from the Model components. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 65 Observer pattern: design “View” classes

COMP 345 - Advanced Program Design with C++ 65 Observer pattern: design “View” classes “Model” classes Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 66 Observer pattern: design • The

COMP 345 - Advanced Program Design with C++ 66 Observer pattern: design • The participants classes in the Observer pattern are: • Subject - interface or abstract class defining the operations for attaching and de-attaching observers to the client. It is often referred to as “Observable”. • Concrete. Subject - concrete Subject class. It maintain the state of the observed object and when a change in its state occurs it notifies the attached Observers. If used as part of MVC, the Concrete. Subject classes are the Model classes that have Views attached to them. • Observer - interface or abstract class defining the operations to be used to notify the registered Observer objects. • Concrete. Observer - concrete Observer subclasses that are attached to a particular Subject class. There may be different concrete observers attached to a single Subject that will provide a different view of that Subject. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 67 Observer pattern: behavior • Behavior

COMP 345 - Advanced Program Design with C++ 67 Observer pattern: behavior • Behavior • The client class instantiates the Concrete. Observable object. • Then it instantiates and attaches the concrete observers to it using the methods defined in the Observable interface. • Each time the (observable) state of the subject is changing, it notifies all the attached Observers using the methods defined in the Observer interface. • When a new Observer is added to the application, all we need to do is to instantiate it in the client class and to add attach it to the Observable object. • The classes already created will remain mostly unchanged. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 68 Observer pattern: implementation // Observer.

COMP 345 - Advanced Program Design with C++ 68 Observer pattern: implementation // Observer. h #pragma once class Observer { public: ~Observer(); virtual void Update() = 0; protected: Observer(); }; // Observer. cpp #include "Observer. h" Observer: : Observer(){ }; Observer: : ~Observer(){ }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 69 Observer pattern: implementation #pragma once

COMP 345 - Advanced Program Design with C++ 69 Observer pattern: implementation #pragma once #include <list> using namespace std; class Observer; // Subject. cpp #include "Subject. h" #include "Observer. h" class Subject { public: virtual void Attach(Observer* o); virtual void Detach(Observer* o); virtual void Notify(); Subject(); ~Subject(); private: list<Observer*> *_observers; }; Subject: : Subject(){ _observers = new list<Observer*>; } Subject: : ~Subject(){ delete _observers; } void Subject: : Attach(Observer* o){ _observers->push_back(o); }; void Subject: : Detach(Observer* o){ _observers->remove(o); }; void Subject: : Notify(){ list<Observer *>: : iterator i = _observers->begin(); for (; i != _observers->end(); ++i) (*i)->Update(); }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 70 Observer pattern: implementation //Clock. Timer.

COMP 345 - Advanced Program Design with C++ 70 Observer pattern: implementation //Clock. Timer. cpp #include "Clock. Timer. h" Clock. Timer: : Clock. Timer(): hour(0), minute(0), second(0) { }; Clock. Timer: : ~Clock. Timer(){ }; //Clock. Timer. h void Clock. Timer: : start(int time){ #pragma once for (int i = 1; i <= time; i++) #include "Subject. h" tick(); }; class Clock. Timer : public Subject { void Clock. Timer: : tick(){ public: second++; Clock. Timer(); if (second >= 60){ int get. Hour(){ return hour; }; minute++; second = 0; int get. Minute(){ return minute; }; if (minute >= 60){ int get. Second(){ return second; }; hour++; minute = 0; void start(int time); if (hour >= 24){ void tick(); hour = 0; ~Clock. Timer(); } private: } int hour; // The Observable object notifies int minute; // all its registered observers int second; Notify(); }; }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 71 Observer pattern: implementation //Digital. Clock.

COMP 345 - Advanced Program Design with C++ 71 Observer pattern: implementation //Digital. Clock. cpp #include "Digital. Clock. h" #include "Clock. Timer. h" #include <iostream> using namespace std; //Digital. Clock. h #pragma once #include "Observer. h" #include "Clock. Timer. h" Digital. Clock: : Digital. Clock(){ class Digital. Clock : public Observer { }; public: Digital. Clock: : Digital. Clock(Clock. Timer* s){ Digital. Clock(); //Upon instantiation, attaches itself Digital. Clock(Clock. Timer* s); //to a Clock. Timer ~Digital. Clock(); _subject = s; void Update(); _subject->Attach(this); void display(); }; private: Digital. Clock: : ~Digital. Clock(){ Clock. Timer *_subject; //Upon destruction, detaches itself }; //from its Clock. Timer _subject->Detach(this); }; void Digital. Clock: : Update(){ //Called by Notify() when state of Subject changes display(); }; void Digital. Clock: : display(){ int hour = _subject->get. Hour(); int minute = _subject->get. Minute(); int second = _subject->get. Second(); cout << hour << ": " << minute << ": " << second << endl; }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 72 Observer pattern: implementation // Clock.

COMP 345 - Advanced Program Design with C++ 72 Observer pattern: implementation // Clock. Driver. cpp #include "Clock. Timer. h" #include "Digital. Clock. h" #include <iostream> using namespace std; int main(void) { //Create a Clock. Timer to be observed Clock. Timer *timer = new Clock. Timer; //Create a Digital. Clock that is connected to the Clock. Timer Digital. Clock *digital. Clock = new Digital. Clock(timer); //Advancing the Clock. Timer updates the Digital. Clock //as tick() calls Update() after it changed its state int secs; cout << "Enter number of seconds to count: "; cin >> secs; timer->start(secs); int j; cin >> j; return 0; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 73 Click to edit Master title

COMP 345 - Advanced Program Design with C++ 73 Click to edit Master title style Strategy pattern Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 74 Strategy pattern • Motivation: •

COMP 345 - Advanced Program Design with C++ 74 Strategy pattern • Motivation: • Sometimes we may want to change the behavior of an object depending on some conditions that are only to be determined at runtime, or to easily add new definitions of a certain behavior without altering the class that is using it. • • Intent: • Define a group of algorithms that applies to a family of classes • Encapsulate each algorithm separately • Make the algorithms interchangeable within that family • Consequence: • The Strategy Pattern lets the specific algorithm implemented by a method vary without affecting the clients that use it. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 75 Strategy pattern • Elements of

COMP 345 - Advanced Program Design with C++ 75 Strategy pattern • Elements of the strategy pattern: • Context Class: class that uses a certain behavior that is to be changed during execution. It contains a Strategy object and provides a set. Strategy() method to change its own strategy. The strategy is to be called through a compute() method that will delegate to a concrete strategy method. • Strategy Abstract Class: Superclass of all strategies containing the abstract compute() method to be implemented by all its subclasses. • Concrete Strategies: Subclasses of Strategy that provide a different implementation for the compute() method. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 76 Strategy pattern: example /** *

COMP 345 - Advanced Program Design with C++ 76 Strategy pattern: example /** * Class configured with a Concrete. Strategy object and maintains * a reference to a Strategy object. Depending on which strategy is * plugged in, it will execute a different operation. */ class Calculator { private: Strategy *strategy; public: Calculator(){}; /** * Plugs in a specific strategy to be used */ Calculator(Strategy *init. Strategy){ this->strategy = init. Strategy; } void set. Strategy(Strategy *new. Strategy){ this->strategy = new. Strategy; } /** * Method that executes a different strategy depending on what strategy was * plugged in upon instantiation. */ int execute. Strategy(int a, int b){ return this->strategy->execute(a, b); } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 77 Strategy pattern: example /** *

COMP 345 - Advanced Program Design with C++ 77 Strategy pattern: example /** * The classes that implement a concrete strategy should inherit this. * The Calculator class uses this to use a concrete strategy. */ class Strategy { public: /** * Method whose implementation varies depending on the strategy adopted. */ virtual int execute(int a, int b) = 0; }; /** * A concrete Strategy that implements a addition operation */ class Add : public Strategy { public: int execute(int a, int b){ cout << "Called Add's execute()" << endl; return a + b; /** } * A concrete Strategy that implements a subtraction operation }; */ class Subtract : public Strategy { public: int execute(int a, int b){ cout << "Called Subtract's execute()" << endl; return a - b; /** } * A concrete Strategy that implements a multiplication operation }; */ class Multiply : public Strategy { public: int execute(int a, int b){ cout << "Called Multiply's execute()" << endl; return a * b; } }; Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 78 Strategy pattern: example int main(){

COMP 345 - Advanced Program Design with C++ 78 Strategy pattern: example int main(){ Calculator calculator(new Add()); int result. A = calculator. execute. Strategy(3, 4); calculator. set. Strategy(new Subtract()); int result. B = calculator. execute. Strategy(3, 4); calculator. set. Strategy(new Multiply()); int result. C = calculator. execute. Strategy(3, 4); cout << "Result of addition strategy: " << result. A << endl; cout << "Result of subtraction strategy: " << result. B << endl; cout << "Result of multiplication strategy: " << result. C << endl; system("PAUSE"); return EXIT_SUCCESS; } Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017

COMP 345 - Advanced Program Design with C++ 79 References • Christopher Alexander, Sara

COMP 345 - Advanced Program Design with C++ 79 References • Christopher Alexander, Sara Ishikawa, Murray Silverstein, Max Jacobson, Ingrid Fiksdahl-King, and Shlomo Angel. A Pattern Language. Oxford University Press, New York, 1977. • Alexander, Christopher. The Timeless Way of Building. Oxford University Press, 1977. ISBN 978 -0 -19 -502402 -9. • Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns – Elements of Reusable Object-Oriented Software, Adisson-Wesley, 1995. Concordia University Department of Computer Science and Software Engineering Joey Paquet, 2007 -2017