Design Patterns Solving problems with already known solutions Unit - 13.

Slides:



Advertisements
Similar presentations
Engineering Problem Solving With C++ An Object Based Approach Additional Topics Chapter 10 Programming with Classes.
Advertisements

Operator overloading redefine the operations of operators
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Design Patterns David Talby. This Lecture Representing other objects Proxy, Adapter, Façade Re-routing method calls Chain of Responsibility Coding partial.
Chapter 6: Using Design Patterns
Façade Pattern Jeff Schott CS590L Spring What is a façade? 1) The principal face or front of a building 2) A false, superficial, or artificial appearance.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Definition Class In C++, the class is the construct primarily used to create objects.
Lecture From Chapter 6 & /8/10 1 Method of Classes.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
Chapter 12: Adding Functionality to Your Classes.
Java and C++, The Difference An introduction Unit - 00.
Design Patterns David Talby. This Lecture n Re-Routing Method Calls u Proxy, Chain of Responsibility n Working with external libraries u Adapter, Façade.
Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 6: Using Design Patterns 1.
Mediator Pattern and Multiuser Protection Billy Bennett June 8 th, 2009.
Case Study - Fractions Timothy Budd Oregon State University.
Defining New Types Lecture 21 Hartmut Kaiser
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Facade Introduction. Intent Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the.
Computing IV Singleton Pattern Xinwen Fu.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Object Oriented Programming (OOP) Lecture No. 11.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
Programming in Java CSCI-2220 Object Oriented Programming.
Introduction to Design Patterns. Questions What is a design pattern? Who needs design patterns? How different are classes and objects in APL compared.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
FacadeDesign Pattern Provide a unified interface to a set of interfaces in a subsystem. Defines a high level interface that makes the subsystem easier.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Design Patterns Introduction
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
CS Class 19 Today  Practice with classes Announcements  Turn in algorithm for Project 5 in class today  Project 5 due 11/11 by midnight – .
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
The Facade Pattern (Structural) ©SoftMoore ConsultingSlide 1.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
Singleton Pattern Presented By:- Navaneet Kumar ise
OBJECT ORIENTED PROGRAMMING. Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism.
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Constructors, Copy Constructors, constructor overloading, function overloading Lecture 04.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
1 Introduction to Object Oriented Programming Chapter 10.
YG - CS Concept of Encapsulation What is encapsulation? - data and functions/methods are packaged together in the class normally.
Topics Instance variables, set and get methods Encapsulation
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
1 Data Structures CSCI 132, Spring 2014 Lecture 2 Classes and Abstract Data Types Read Ch Read Style Guide (see course webpage)
Copyright © 2012 Pearson Education, Inc. Chapter 10 Advanced Topics.
1 C++ Classes & Object Oriented Programming Overview & Terminology.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Creational Patterns C h a p t e r 3 – P a g e 14 Creational Patterns Design patterns that deal with object creation mechanisms and class instantiation,
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
1 Lecture Material Design Patterns Visitor Client-Server Factory Singleton.
Examples (D. Schmidt et al)
1/23/2018 Design Patterns David Talby.
Design Patterns Lecture part 2.
Software Design & Documentation
Creational Pattern: Prototype
Review: Two Programming Paradigms
Classes and Data Abstraction
Object Oriented Programming (OOP) Lecture No. 11
Presentation transcript:

Design Patterns Solving problems with already known solutions Unit - 13

Unit Introduction This unit covers design patterns using C++

Unit Objectives After covering this unit you will understand… What are design patterns What are design patterns Singleton design pattern Singleton design pattern Factory design pattern Factory design pattern Proxy design pattern Proxy design pattern Facade design pattern Facade design pattern

Design Patterns A design pattern is a special way of solving a particular class of problems A design pattern is a special way of solving a particular class of problems A design pattern has four essential elements A design pattern has four essential elements The Pattern Name is a handle, which is used to describe a design problem, its solution and consequences. The Pattern Name is a handle, which is used to describe a design problem, its solution and consequences. The Problem describes, when to apply the pattern The Problem describes, when to apply the pattern

Design Patterns (contd.) The Solution describes the elements the makeup the design, their responsibilities, and collaborations The Solution describes the elements the makeup the design, their responsibilities, and collaborations The Consequences are the results and trade off of applying the pattern The Consequences are the results and trade off of applying the pattern

Singleton This pattern is a way to provide, one and only one instance of an object This pattern is a way to provide, one and only one instance of an object Prevent from having any way to create an object except the provided way Prevent from having any way to create an object except the provided way Declare all constructors as private, and create at least one constructor to prevent the compiler from synthesizing a default constructor Declare all constructors as private, and create at least one constructor to prevent the compiler from synthesizing a default constructor

Example: Singleton #include #include class Singleton { private: private: static Singleton sm_s; static Singleton sm_s; int m_i; Singleton(int x) : m_i(x) { } Singleton(int x) : m_i(x) { } public: public: static Singleton& GetHandle() { return sm_s;} int GetValue() { return m_i; } int GetValue() { return m_i; } void SetValue(int x) { m_i = x; } void SetValue(int x) { m_i = x; }}; Singleton Singleton::sm_s(47); // initialize static member // variable // variable

Example: Singleton (contd.) void main() { Singleton& sObj = Singleton::GetHandle(); Singleton& sObj = Singleton::GetHandle(); cout << sObj.GetValue() << endl; // prints 47 cout << sObj.GetValue() << endl; // prints 47 Singleton& sObj2 = Singleton::GetHandle(); Singleton& sObj2 = Singleton::GetHandle(); sObj2.SetValue(9); sObj2.SetValue(9); cout << sObj.GetValue() << endl; // prints 9 cout << sObj.GetValue() << endl; // prints 9}

Factory Encapsulate object creation Encapsulate object creation Create objects through a common interface rather than to allow the creation code to be spread throughout program Create objects through a common interface rather than to allow the creation code to be spread throughout program All the code in a program must go through factory whenever it needs to create one of objects All the code in a program must go through factory whenever it needs to create one of objects Adding a new object modifies factory Adding a new object modifies factory

Example: Factory #include #include class Shape { public: public: virtual void Draw() = 0; virtual void Draw() = 0; virtual void Erase() = 0; virtual void Erase() = 0; virtual ~Shape() {} virtual ~Shape() {} class BadShapeCreation : public exception class BadShapeCreation : public exception{ string m_reason; string m_reason; public: public: BadShapeCreation(string type) BadShapeCreation(string type){

Example: Factory (contd.) m_reason = "Cannot create type "+ type; } ~BadShapeCreation() throw() {} ~BadShapeCreation() throw() {} const char *what() const throw() const char *what() const throw(){ return m_reason; return m_reason; } }; }; static Shape* Factory(string type) // exception handle static Shape* Factory(string type) // exception handle throw(BadShapeCreation); throw(BadShapeCreation); }; // declaration of Shape class ends here class Circle : public Shape { Circle() {} // Private constructor Circle() {} // Private constructor friend class Shape; friend class Shape;

Example: Factory (contd.) public: public: void Draw() { cout << "Circle::draw\n"; } void Draw() { cout << "Circle::draw\n"; } void Erase() { cout << "Circle::erase\n"; } void Erase() { cout << "Circle::erase\n"; } ~Circle() { cout << "Circle::~Circle\n"; } ~Circle() { cout << "Circle::~Circle\n"; }}; class Square : public Shape { Square() {} Square() {} friend class Shape; friend class Shape; public: public: void Draw() { cout << "Square::draw\n"; } void Draw() { cout << "Square::draw\n"; } void Erase() { cout << "Square::erase\n"; } void Erase() { cout << "Square::erase\n"; } ~Square() { cout << "Square::~Square\n"; } ~Square() { cout << "Square::~Square\n"; }}; Shape* Shape::Factory(string type) // exception handle throw(Shape::BadShapeCreation) throw(Shape::BadShapeCreation)

Example: Factory (contd.) { if(type == "Circle") return new Circle; if(type == "Circle") return new Circle; if(type == "Square") return new Square; if(type == "Square") return new Square; throw BadShapeCreation(type); throw BadShapeCreation(type);} char* p_Shlist[] = { "Circle", "Square", "Square", "Circle", "Circle", "Circle", "Square", "" }; "Circle", "Circle", "Circle", "Square", "" }; void main() { vector shapes; vector shapes; try try { for(char** cp = p_Shlist; **cp; cp++) for(char** cp = p_Shlist; **cp; cp++) shapes.push_back(Shape::Factory(**cp)); shapes.push_back(Shape::Factory(**cp)); } }

Example: Factory (contd.) catch(Shape::BadShapeCreation e) catch(Shape::BadShapeCreation e) { cout << e.what() << endl; cout << e.what() << endl; return 1; return 1; } } for(int i = 0; i < shapes.size(); i++) for(int i = 0; i < shapes.size(); i++) { shapes[i]->Draw(); shapes[i]->Draw(); shapes[i]->Erase(); shapes[i]->Erase(); } }}

Proxy Proxy pattern is used to control access to the actual implementation Proxy pattern is used to control access to the actual implementation Proxy is a surrogate class that hides the implementation class Proxy is a surrogate class that hides the implementation class A call made to proxy class is delegated to the implementation class A call made to proxy class is delegated to the implementation class

Example: Proxy #include #include class Graphic { public: public: virtual ~Graphic(); virtual ~Graphic(); virtual void Draw (const Point& at) = 0; virtual const Point& GetExtent() = 0; virtual void Load (istream& from) = 0; protected: protected:Graphic();}; class Image : public Graphic {

Example: Proxy (contd.) public: public: Image(const char* p_File);// Load Image from File Image(const char* p_File);// Load Image from File virtual ~Image(); virtual void Draw (const Point& at); virtual const Point& GetExtent(); virtual void Load (istream& from); private: private: // own private data }; class ImageProxy : public Graphic { public: public: ImageProxy(const char* p_File);// Load Image from File ImageProxy(const char* p_File);// Load Image from File virtual ~ImageProxy(); virtual void Draw (const Point& at);

Example: Proxy (contd.) virtual const Point& GetExtent(); virtual void Save (ostream& to); protected: protected: Image* GetImage(); private: private: // own private data Image* m_pImage; Point m_Extent; char* m_pFileName; }; ImageProxy::ImageProxy(const char* p_FileName) { m_pFileName = strdup(p_Filename); m_pFileName = strdup(p_Filename); m_Extent = Point::Zero;// Don’t know extent yet m_Extent = Point::Zero;// Don’t know extent yet m_pImage = new Image(m_pFileName); m_pImage = new Image(m_pFileName);}

Example: Proxy (contd.) const Point& ImageProxy::GetExtent() { if (m_Extent == Point::Zero) if (m_Extent == Point::Zero) { m_Extent = GetImage()->GetExtent(); m_Extent = GetImage()->GetExtent(); } return m_Extent; return m_Extent;} void ImageProxy::Draw(const Point& at) { GetImage()->Draw(at); GetImage()->Draw(at);}

Example: Proxy (contd.) void ImageProxy::Load (istream& from) { from >> m_Extent >> m_pFileName; from >> m_Extent >> m_pFileName;} class TextDocument { public: public:TextDocument(); void Insert(Graphic*); //… more functions }; void main() { TextDocument* p_Text = new TextDocument; TextDocument* p_Text = new TextDocument; p_Text->Inert(new ImageProxy(“AnImageFile.jpg”)); p_Text->Inert(new ImageProxy(“AnImageFile.jpg”));}

Facade Provide a unified interface to a set of interfaces in a subsystem Provide a unified interface to a set of interfaces in a subsystem Defines a higher level interface the makes the sub systems easier to use Defines a higher level interface the makes the sub systems easier to use Facade reduces the complexity Facade reduces the complexity Minimise communication and dependencies among sub systems Minimise communication and dependencies among sub systems Useful when layering sub systems Useful when layering sub systems

Example: Facade include include // following classes perform different functions required for // compiling a program class Scanner// Reads input {}; class Parser // Parse input {}; class ProgramNodeBuilder // Build Nodes {}; class CodeGenerator // Generates code {};

Example: Facade (contd.) class Compiler { public: public:Compiler(); virtual void Compile(istream&, BytecodeStream&); }; // Facade implementation void Compiler::Compile(istream& input, BytecodeStream outp) { Scanner scanner(input); Scanner scanner(input); ProgramNodeBuilder builder; ProgramNodeBuilder builder; Parser parser; Parser parser; parser.Parse(scanner, builder); parser.Parse(scanner, builder); RISCCodeGenerator generator(outp); RISCCodeGenerator generator(outp);}

Unit Summary In this unit you have covered … In this unit you have covered … What are design patterns What are design patterns Singleton, Factory, Proxy and Facade design patterns using C++ Singleton, Factory, Proxy and Facade design patterns using C++