Behavioral Pattern: Command C h a p t e r 5 – P a g e 139 There are times when the need arises to issue a request to an object without knowing anything.

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms
Advertisements

Computer Programming Basics Assistant Professor Jeon, Seokhee Assistant Professor Department of Computer Engineering, Kyung Hee University, Korea.
Behavioral Pattern: Template Method C h a p t e r 5 – P a g e 217 On occasion, two different components in a software system will have significant similarities,
True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Programming Switch command. COMP102 Prog. Fundamentals: Switch command / Slide 2 Multiple Selection: The switch Statement value1 action 1 value2 action.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Command Pattern Chihung Liao Cynthia Jiang. Waiter Order Execute() Hamburger Execute() Hot Dogs Execute() Fries Execute() Cook Make Food()
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
C++ fundamentals.
Behavioral Patterns C h a p t e r 5 – P a g e 128 BehavioralPatterns Design patterns that identify and realize common interactions between objects Chain.
BY VEDASHREE GOVINDA GOWDA
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Computer Programming and Basic Software Engineering 9 Building Graphical User Interface Working with Unmanaged Code.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
CS 114 – Class 02 Topics  Computer programs  Using the compiler Assignments  Read pages for Thursday.  We will go to the lab on Thursday.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Selection Statements in C++ If Statement in C++ Semantics: These statements have the same meaning as in the algorithmic language. 2- Two way selection:
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
February 11, 2005 More Pointers Dynamic Memory Allocation.
Command. RHS – SOC 2 Executing a command Executing a command appears simple at first, but many details to consider: –Who creates a command? –Who invokes.
CPSC 252 Concrete Data Types Page 1 Overview of Concrete Data Types There are two kinds of data types: Simple (or atomic) – represents a single data item.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Fundamental Programming: Fundamental Programming Introduction to C++
1 Writing a Good Program 8. Elementary Data Structure.
Previously Repetition Structures While, Do-While, For.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Dynamic memory allocation and Pointers Lecture 4.
CSC1201: PROGRAMMING LANGUAGE 2 Aseel Al Hadlaq 2nd Term
Looping and Counting Lecture 3 Hartmut Kaiser
Behavioral Pattern: Strategy C h a p t e r 5 – P a g e 205 The Open-Closed Principle advocates designing software in such a way that it will absorb new.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Command Pattern.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
C++ Classes and Data Structures Jeffrey S. Childs
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 5: Continuing with C++ I/O Basics.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Review 1 List Data Structure List operations List Implementation Array Linked List.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Creational Pattern: Builder When a complex object needs to be created, it is sometimes beneficial to separate the construction of the object from its.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
1 ICS103 Programming in C Lecture 8: Functions I.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
1 n Object Oriented Programming. 2 Introduction n procedure-oriented programming consists of writing a list of instructions and organizing these instructions.
Command Pattern. Intent encapsulate a request as an object  can parameterize clients with different requests, queue or log requests, support undoable.
A bit of C programming Lecture 3 Uli Raich.
Command Line Arguments
Command Pattern.
Introduction to Functions
Compound Assignment Operators in C++
Chapter 4: Control Structures I (Selection)
Control Structures Part 3
Looping III (do … while statement)
Fundamental Programming
COMS 261 Computer Science I
Today’s Objectives 28-Jun-2006 Announcements
Modifying Objects Assignment operation Assignment conversions
Programming Strings.
Presentation transcript:

Behavioral Pattern: Command C h a p t e r 5 – P a g e 139 There are times when the need arises to issue a request to an object without knowing anything about the operation being requested or the object receiving the request. The Command Pattern encapsulates the request as an object, which allows clients to be parameterized with different requests, requests to be logged or queued, and undoable operations to be supported.

The Command Pattern C h a p t e r 5 – P a g e 140 The Command declares an interface for executing an operation. The ConcreteCommand defines a binding between a Receiver object and an action, implementing Execute by invoking the corresponding operation on the Receiver. The Client creates a ConcreteCommand object and sets its Receiver. The Invoker asks the Command to carry out the request. The Receiver knows how to perform the operations associated with carrying out the request.

C h a p t e r 5 – P a g e 141 Non-Software Example: Diner The Waitress (invoker) generates an Order (concrete command) based upon what the Customer (client) selects from the menu, placing the order on a Check (command). The Order is then queued for the Cook (receiver) and, after being executed, the Order is delivered to the Customer. Note that the pad of “checks” used by each waitress is not dependent on the menu, so they can support commands to cook many different items.

C h a p t e r 5 – P a g e 142 Software Example: Integer Conversion This C++ code will convert an integer into binary, octal, or hexadecimal, but its design is rather rigid. int num; char ch; char tryAgain = 'y'; string output; do { cout << "Enter an integer value: "; cin >> num; cout << "Enter a conversion type " << " (b=binary, o=octal, h-hexadecimal): "; cin >> ch; switch( toupper(x) ) { case 'O': { output = to_oct(num); break; } case 'H': { output = to_hex(num); break; } case 'B': { output = to_bin(num); break; } default: { output = "invalid"; } } cout << "Result: " << output << endl << endl; cout << "Try again? (Y or N) "; cin >> tryAgain; } while ( (tryAgain == 'Y') || (tryAgain == 'y') ); Every time the operations change, the switch block needs to be modified. At the moment, operations are just functions which exist completely independently of each another, even though they're all in fact fairly similar, and selection is solely based on different character values. (These character values acting like runtime identifiers for the operations.) A better solution would build in some kind of relationship between all the operations, and tag each one with their character value identifier.

C h a p t e r 5 – P a g e 143 Integer Conversion With The Command Pattern By separating the conversion command from the object that performs it (the convertor), the total amount of code will undoubtedly increase, but the revised design breaks bigger problems down into sub-problems, producing small, reusable modules in the process.

C h a p t e r 5 – P a g e 144 Command-Based Integer Conversion Code in C++ #include #include // Enables the determination of bit lengths #include // Enables the creation/loading of string-streams #include // Enables the mapping of dictionary pairs using namespace std; class converter { public: virtual std::string convert(int) = 0; virtual ~converter() {} }; class hex_converter : public converter { public: std::string convert(int i) { std::stringstream ss; ss << std::hex << i; return ss.str(); } };

C h a p t e r 5 – P a g e 145 class oct_converter : public converter { public: std::string convert(int i) { std::stringstream ss; ss << std::oct << i; return ss.str(); } }; class bin_converter : public converter { public: std::string convert(int i) { std::bitset bits(i); std::stringstream ss; ss << bits; return ss.str(); } };

C h a p t e r 5 – P a g e 146 class dictionary { public: // The dictionary is loaded with the three character/converter pairs dictionary() { dict.insert( std::make_pair( 'B', new bin_converter ) ); dict.insert( std::make_pair( 'O', new oct_converter ) ); dict.insert( std::make_pair( 'H', new hex_converter ) ); } converter* lookup(char x) { std::map ::const_iterator iter; iter = dict.find( toupper(x) ); if ( iter != dict.end() ) return iter->second; else return NULL; } ~dictionary() { while( dict.begin() != dict.end() ) { delete dict.begin()->second; dict.erase( dict.begin() ); } private: // The STL library enables mapping between objects // between two types. In this case, the three user-entered // characters have corresponding converters, and this // mapping is used to create a dictionary between them. std::map dict; };

C h a p t e r 5 – P a g e 147 void main() { int num; char ch; char tryAgain = 'y'; string output; dictionary dict; do { cout << "Enter an integer value: "; cin >> num; cout << "Enter a conversion type (b=binary, o=octal, h-hexadecimal): "; cin >> ch; converter* con = dict.lookup( ch ); if ( con != NULL ) output = con->convert( num ); else output = "Invalid"; cout << "Result: " << output << endl << endl; cout << "Try again? (Y or N) "; cin >> tryAgain; } while ( (tryAgain == 'Y') || (tryAgain == 'y') ); }

Command Pattern Advantages C h a p t e r 5 – P a g e 148 The object that creates a command (the Client) is not the same object that executes it (the Invoker). This separation provides flexibility in the timing and sequencing of commands. Materializing commands as objects means they can be passed, staged, shared, loaded in a table, and otherwise instrumented or manipulated like any other object. Command objects can be thought of as "tokens" that are created by one entity that knows what needs to be done, and passed to another entity that has the resources for doing it. Another of the main reasons for using the Command Pattern is that it provides a convenient way to store and execute an Undo function. Each command object can remember what it just did and restore that state when requested to do so if the computational and memory requirements are not too overwhelming.