sse658.3_Phillips-Slipak


 * Course:** SSE658
 * Project:** 3
 * Subject:** State, Proxy, Template, and Model-View-Controller Design Patterns
 * Student:** David Phillips, Dmitriy Slipak
 * E-mail:** drphillips45@gmail.com, dslipak@gmail.com

=Table Of Content=

 =1. Introduction=
 * 1) Introduction
 * 2) State Pattern
 * 3) Proxy Pattern
 * 4) Template Pattern
 * 5) Model-View-Controller Pattern
 * 6) Mixed Patterns
 * 7) Conclusion
 * 8) References

The purpose of this project is to continue learning different design patterns and how they can enhance software engineering and application projects through code reuse and proven, stable patterns. For this project the goal is to develop four patterns and discuss their benefits and uses. There four patterns we selected are State, Proxy, Template, and Model-View-Controller. Those are some important and useful patterns in the set of compound patterns. Each pattern will be explained in details. Examples, presented for each pattern, will demonstrate ability of applying in the code.

Another goal is to combine different patterns in a simple project. We will demonstrate patterns combination in the example of a traffic signal light. The objective is to have the signal light change states, from green, to yellow to red to green, as well as update GUI according to particular state.  =2. State Pattern=


 * //Definition//**

According to Wikipedia the definition is: "This pattern is used in computer programming to represent the state of an object." [4] This definition is simple and straight forward. The pattern simply provides a way to change the state of an object.


 * //Classification//**

The state pattern is classified as a behavioral pattern. Since it does change the behavior of the object when it changes state. Most often when the state changes there is some method that will change the behavior of the object as well. Looking at the implementation of the code we can see that when the state changes from Red to Green, the color changes, and fro our example a message tot he user indicating the state has been changed from red to green is displayed.


 * //Intent//**

During all of our careers we have all written code that makes use of switch statements and if-then-else constructs. In many cases these are the appropriate constructs to use. However there are times when these can be done away with. This is where the state pattern comes into play. The state pattern is classified as a behavior design pattern, meaning it changes the behavior of the object. The Gang of Four (GoF) book says that the State design pattern will "Allow an object to alter its behavior when its internal state changes. The object will appear to change its class." [1]

"When you use the State pattern, any part of your code can check what state is current. That can clarify and centralize the workings of very large pieces of code because you have control over what far-flung code segments do, just by changing the current state." [2]

"In general, the State pattern is useful when you've got a lot of code that's getting more and more murky and complex. If you can compartmentalize the working of what you're trying to do into a set of independent states, you can compartmentalize your code." [2]

The intent of the state class is to allow the object to alter its behavior when it's internal state changes. In traditional procedural programming this is often done using switch statements and if-then-else statements. Although this works, it is often times hard to maintain and when additional states need to be added, this becomes difficult and unwieldy.


 * //Motivation//**

The key idea in this pattern is to introduce an abstract class to represent the states of the objects. When using a state pattern in Object Oriented programming each state is an object with its associated behaviors. The state will hold a reference to a state and delegates all state dependent behaviors to its current state. Take for example a traffic light; the light has three normal states, red/stop, yellow/caution, and green/go. When could program this is a switch statement so when an appropriate even occurs, either times or sensors activation, the state of the light would change from red to green. For the purpose of this application and discussion I will not go into the other states a signal might have, such a flashing red.

code format="cpp" switch(i) {           case 0: SignalState-> Red; break; case 1: SignalState-> Yellow; break; case 2: SignalState-> Green; break; default: break; } code

This process would work fine for simple discussion or states but what if we had an application with an unknown amount of states and behaviors? You can quickly see how this could become very difficult to maintain. Take for example a calculator application. You could be asked to create a simple calculator that would consist of just the basic functions of adding, subtracting, multiplication, and division. After you have completed the application using procedural programming, because it was quick and easy, the customer comes back and tells you to add a couple of functions such as adding to memory, recalling memory, and deleting memory. So you add those features still in the procedural, after all it was only three more. As we all know requirements creep up if allowed, so just before you finish the application they came back and say to add all the scientific functionality such as sin, cos, tan, square roots, squaring and cubing a entry, etc. You quickly realize there has to be a better way. After all; the switch statement is becoming quite large now. Well this is the beauty of the state pattern.


 * //Applicability//**

According to GoF, use the State pattern in either of the following cases:
 * An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.
 * Operations have large, multi-part conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects. [3]


 * //Structure//**

The structure of the state pattern is pretty straightforward as well. In the image bellow we can see that the main control object initiates a state change. It connects to the state object, which in turn calls a state class and performs the applicable behavior change based on the business rules of the application.


 * //Participants//**

From the diagram above we can see the state pattern has three participants. This includes the Context, State, and ConcretesState classes. In a more robust application that utilizes the state pattern there may be a lot of concrete classes depending on the number of states the application has to handle.


 * //Advantages//**

Benefits:
 * Puts all behavior associated with a state into one object
 * Allows state transition logic to be incorporated into a state object rather than in a monolithic if or switch statement
 * Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes [2]


 * //Disadvantages//**

One of the biggest disadvantage of the state pattern is it requires an increased number of objects. If you were coming from a procedural code, re-factoring into an Object Oriented application may seem daunting when applying this pattern. It really isn't that bad though if you know your way around Object Oriented programming. [2]


 * //Implementation//**

During the brief description of the state pattern above I've already started the implementation of my state pattern. Looking back in the motivation section of this report, we can see that using procedural code, although can be useful but more realistically is it better to use the state a pattern. Thus applying the state pattern to the signal light example code shown above, the code can be written like this:

code format="cpp" (fsm.*ptrs[num]); code

Of course this is not all that is required to create the state pattern. However, with this code you can simply pass the desired state, in this case in the form of a number, and then let the state object call the appropriate object and the behavior associated with that object. Of course we have to create the objects and the behaviors. Before I create the signal light state objects, I'll create the Signal and State classes.

code format="cpp" class Signal { class State *current; public: Signal;

void setCurrent(State *s) {      current = s;    }

void green; void red; void yellow; };

class State { public: virtual void green(Signal *m) {       cout << "   already GREEN" << endl; }   virtual void red(Signal *m) {       cout << "   already RED" << endl; }

virtual void yellow(Signal *m) {       cout << "   already YELLOW" << endl; } }; code

For the sake of this discuss I've kept the state very simple. If the method is called then the state was already in the curt rent state. I just let the user know this for illustrative purposes. Now I will create the objects such as, Red, Green, and Yellow as shown here:

code format="cpp" class GREEN: public State { public: void yellow(Signal *m); };

class YELLOW: public State { public: void red(Signal *m); };

class RED: public State { public: void green(Signal *m) {       cout << "   going from RED to GREEN" << endl; m->setCurrent(new GREEN); delete this; } }; code

Each of these classes has methods in them that will fire when the object is called. Other methods are also created and will be shown in the full code listing at the end of this section.

In order for this to work the objects and methods need to be called. In order to do this I created an simple while loop and asked the user to enter a 0, 1, or a 2 to change the state. In the real signal light systems this would be an example of a sensor activation to change the state of the light. Since the use can enter the numbers in any sequence the normal transitions you would normally see in a real signal light will not always hold true. For example the user could go from yellow to green.

code format="cpp" void(Signal:: *ptrs[]) = {   &Signal::red, &Signal::green, &Signal::yellow };

Signal fsm; int num, a; while (1) {   cout << "Enter 0/1/2" << endl; cin >> num; if (num == 0 || num < 3) **(fsm.*ptrs[num]);** else break; } code

The bold line of code is the call to change the state of the object. It actually goes to one of the methods associated with the object and applies the change of state there. Let’s see what a quick run would look like:



The initial state is Red, when the user presses 0 the application checks and sees that state is already Red and responds appropriately; now when the user clicks 1, the state changes from Red to Green. Although not shown here, the user can press the 2 key and the state will change from Green to Yellow. The flow goes like this: The fsm object obtains the pointer from:

code format="cpp" void(Signal:: *ptrs[]) = {  &Signal::red, &Signal::green, &Signal::yellow }; code

It then calls the void Signal :: green method. This method has a call to current->green(this). This line of code will now call the Red Class’s void green ( Signal * m ) method, which set the new state to green with this line: m - > setCurrent ( new GREEN ) ;.

The full code listing is shown here:

code format="cpp" // myState.cpp : Defines the entry point for the console application. //


 * 1) include "stdafx.h"
 * 2) include 
 * 3) include

using namespace std;

class Signal { class State *current; public:

Signal;

void setCurrent(State *s) {           current = s;        }

void green; void red; void yellow; };

class State { public: virtual void green(Signal *m) {       cout << "   already GREEN" << endl; }   virtual void red(Signal *m) {       cout << "   already RED" << endl; }

virtual void yellow(Signal *m) {       cout << "   already YELLOW" << endl; } };

void Signal::green {   cout << "Green"; current->green(this); }

void Signal::red {   cout << "RED"; current->red(this); }

void Signal::yellow {   cout << "Yellow"; current->yellow(this); }

class GREEN: public State { public: void yellow(Signal *m); };

class YELLOW: public State { public: void red(Signal *m); };

class RED: public State { public: void green(Signal *m) {       cout << "   going from RED to GREEN" << endl; m->setCurrent(new GREEN); delete this; } };

void GREEN::yellow(Signal *m) {   cout << "   going from GREEN to YELLOW" << endl; m->setCurrent(new YELLOW); delete this; }

void YELLOW::red(Signal *m) {   cout << "   going from YELLOW to RED" << endl; m->setCurrent(new RED); delete this; }

Signal::Signal {   cout << "Red"; current = new RED; cout << endl; }

int _tmain(int argc, _TCHAR* argv[]) {   void(Signal:: *ptrs[]) = {       &Signal::red, &Signal::green, &Signal::yellow };

Signal fsm; int num, a;   while (1) {       cout << "Enter 0/1/2" << endl; cin >> num; if (num == 0 || num < 3) (fsm.*ptrs[num]); else break; }

system("Pause"); return 0; } code

Dmitiry and I have combines this state code with MVC pattern he developed into an mvcState application that display in a graphical way a signal light that. This is just an example of how this pattern along with other patterns can be combined into an application.  =3. Proxy Pattern=


 * //Definition//**

According to wikipedia a basic definition of the proxy pattern is, "A proxy, in its most general form, is a class functioning as an interface to something else." [5] In some way this may seem odd, why create another object just to call an object that is already created? Often times the main object can be quite complex and take a lot of resources. If the object had to be instantiate numerous times ti can become quite expensive. With the proxy object, they just contains a reference to the more complex object and thus reduce the overhead substantially. The proxy pattern is also called the surrogate pattern.


 * //Classification//**

The proxy pattern belongs the structural class of design patterns. [5]


 * //Intent//**

The intent of the proxy pattern is to provide a surrogate or placeholder for another object to control access to it.


 * //Motivation//**

One reason for controlling access to an object is to defer the full cost of its creation and initialization until we actually need to use it. In many cases there are situations in which the full object does not need to be initialized, this is when the proxy pattern comes into play. It helps reduce the overall cost during program execution by allowing a lighter weight object to call the main object


 * //Applicability//**

There are many reasons why the proxy pattern is useful especially in the case of distributed system and networks. Other applicable uses for the proxy patter are: [3]
 * Widely applicable in almost every distributed system or infrastructure for distributed systems uses the pattern to represent remote components locally.
 * Applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer.
 * Depending upon the situation, applications dealing with the respected Proxy patterns are applicable. Like the Remote proxy, Virtual Proxy, and Protection Proxy.
 * A Smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed.


 * //Structure//**

The basic structure of the proxy patter looks like the diagram below:

Here you can see the client sends a request to access the Real Subject. This request is routed through the proxy instead.


 * //Participants//**

In the proxy pattern there are three participants, namely: [3]

Proxy
 * maintains a reference that lets the proxy access the real subject. Proxy may refer to a Subject if the Real Subject and Subject interfaces are the same.
 * provides an interface identical to Subject's so that a proxy can be substituted for the real subject.
 * controls access to the real subject and may be responsible for creating and deleting it.
 * other responsibilities depend on the kind of proxy:
 * remote proxies are responsible for encoding a request and its arguments and for sending the encoded request to the real subject in a different address space.
 * virtual proxies may cache additional information about the real subject so that they can postpone accessing it.
 * protection proxies check that the caller has the access permissions required to perform a request.

Subject
 * defines the common interface for Real Subject and Proxy so that a Proxy can be used anywhere a Real Subject is expected.

Real Subject
 * defines the real object that the proxy represents.


 * //Advantages//**

Some of the advantages of the proxy pattern are detailed here: [3]
 * Enhanced Maintainability and Extensibility of the system, which may reduce compilation dependencies promote layering of systems provides weak coupling between clients and subsystems.
 * Copy-on-write can reduce the cost of copying heavyweight subjects significantly
 * The system shall control access to components by interposing an intermediary that evaluates the identity and access privileges of the requestor.
 * The system will support distributed processing by providing a local representative for a component in a different address space.


 * //Disadvantages//**

Some of the disadvantages of the proxy pattern are detailed here: [3]
 * Introduces a level of indirection when accessing an object.
 * Proxy Pattern can hide from the client. It's also called copy-on-write.


 * //Implementation//**

In this implementation I will create a protected class, the real object in this case. In this object methods will be created to accomplish the tasks needed. I've created a simple petty cash withdraw and deposit system. For simplicity sake the main function just has a loop to go through all the employees in the list. It will give many to the employee, thus invoking the withdrawal method, give no money, or if the balance gets too low add money using the deposit method.

The main protected class is shown here:

code format="cpp" class PettyCashProtected {   int balance; public: PettyCashProtected {           balance = 500; }       bool withdraw(int amount) {           if (amount > balance) return false; balance -= amount; return true; }       bool deposit(int amount) {           balance += amount; return true; }       int getBalance {           return balance; } }; code

As you can see the withdrawal, deposit and get balance methods are all contained within this main object. We don't want to call this subject directly so we'll create the proxy class as shown here:

code format="cpp" class PettyCash {   PettyCashProtected pc; public: bool withdraw(Person &p, int amount) {           if (p.name == "Dave" || p.name == "Brenda" || p.name == "Joshua") return pc.withdraw(amount); else return false; }       bool deposit(int amount) {           return pc.deposit(amount); }       int getBalance {           return pc.getBalance; } }; code

Notice the first line of code:

code format="cpp" PettyCashProtected pc; code

This creates the call to the real object. The rest of the proxy is just using this call to gain access to the main or real object thus isolating the main object from the client. This will become clearer in the next block of code. This code is the main block where we instantiate the proxy object and not the real object. Using this proxy we then allow the client to make the withdrawals, deposits and get the balance. How this is done is not contained in the proxy class, only the main class. The proxy class just uses the reference to the main object to complete its tasks.

The main portion of the code is shown here:

code format="cpp" PettyCash pc; Person employee[4]; int amount = 100; cout << "Starting balance is " << pc.getBalance << endl << endl;

for (int i = 0; i < 4; i++) {       if (!pc.withdraw(employee[i], amount)) cout << "No money given for " << employee[i].name << endl; else cout << amount << " given to " << employee[i].name << endl;

amount += 100; }   if (pc.getBalance <= 100) pc.deposit(500); cout << endl << "Remaining balance is " << pc.getBalance << endl;

system("Pause"); return 0; code

The first line of code is the reference to the proxy object and not the real object. I did create a small person class as well. This is shown here:

code format="cpp" class Person {   string sName; static string list[]; static int next; public: Person {           sName = list[next++]; }       string name {           return sName; } }; code

This assisted in utilizing the employee's in order to give them money out of the petty cash application.

Although there was nothing fancy about this pattern, it is still very useful and can saves a lot of resources by calling a smaller less complex and efficient object to make a reference back to the main object. Just remember that when performing memory maintenance that all proxy objects have to be closed before de-allocating the memory utilized by the main object.

I've set up the application to just loop through all the employees in the list. It will withdraw an amount for the employee. If the amount in the petty cash drops below 100 it will add 500. The sample run is shown here:



 =Template Pattern=


 * //Definition//**

A template method is an abstract definition of an algorithm. It defines the algorithm step by step. Each step invokes either an abstract operation or a primitive operation. A subclass fleshes out the algorithm by defining the abstract operations.

The template method pattern is a Gang of Four design pattern. This is a behavioral pattern as it defines a manner for controlling communication between classes or entities. The template method pattern is used to define the basic steps of an algorithm and allow the implementation of the individual steps to be changed. This is similar to the strategy design pattern. The key difference is the ability to vary parts of the algorithm rather than replacing the algorithm in its entirety.

The overall structure of the basic algorithm is defined in an abstract base class. This class may include some real functionality but often just defines the order in which the overridable steps will be executed. The implementations for the steps are defined in subclasses. This use of inheritance promotes loose coupling, as the calling function need not know which algorithm is to be executed. Correct use of the pattern also reduces duplication of code.


 * //Classification//**

Object Behavioral Pattern.


 * //Intent//**

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.


 * //Motivation//**

Average application, designed in object-oriented manner, contains number of classes. There could be a situation, when few classes similar in their basic algorithm (for example the same sequence of operations), but in details, they perform different things. The idea behind the Template pattern is that some parts of an algorithm are well defined and can be implemented in the base class, while other parts may have several implementations and are best left to derived classes. Another main theme is recognizing that there are some basic parts of a class that can be factored out and put in a base class so that they do not need to be repeated in several subclasses.


 * //Applicability//**

The Template Method pattern should be used in following situations:
 * When there is a need to implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.


 * When common behavior among subclasses should be factored and localized in a common class to avoid code duplication. In this case we first identify the differences in the existing code and then separate the differences into new operations. Finally, we replace the differing code with a template method that calls one of these new operations.


 * When there is a need to control subclasses extensions. We can define a template method that calls “hook” operations at specific points, thereby permitting extensions only at those points.


 * //Structure//**

The Template Method pattern can be represented by a diagram below.




 * //Participants//**


 * **Abstract Class** - defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm. Implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in Abstract Class or those of other objects.


 * **Concrete Class** - implements the primitive operations to carry out subclass-specific steps of the algorithm.


 * //Advantages//**


 * **Code reuse**. Template methods are a fundamental technique for code reuse. They are particularly important in class libraries, because they are the means for factoring out common behavior in library classes.


 * **Inverted Control Structure**. Template methods lead to an inverted control structure that's sometimes referred to as "the Hollywood principle", that is, "Don't call us, we'll call you". This refers to how a parent class calls the operations of a subclass and not the other way around.

> Template methods call the following kinds of operations:


 * 1) Concrete operations (either on the Concrete Class or on client classes).
 * 2) Concrete Abstract Class operations (i.e., operations that are generally useful to subclasses).
 * 3) Primitive operations (i.e., abstract operations).
 * 4) Factory methods.
 * 5) Hook operations, which provide default behavior that subclasses can extend if necessary. A hook operation often does nothing by default.

> It's important for template methods to specify which operations are hooks (may be overridden) and which are abstract operations (must be overridden). To reuse an abstract class effectively, subclass writers must understand which operations are designed for overriding.


 * //Disadvantages//**

As a disadvantages for a Template Method pattern following could be considered:


 * Communicates intent poorly
 * Difficult to compose functionality.
 * Difficult to comprehend program flow.
 * Difficult to maintain.


 * //Implementation//**

Following should be considered during the Template Method implementation:


 * **Using C++ access control**. In C++, the primitive operations that a template method calls can be declared protected members. This ensures that they are only called by the template method. Primitive operations that must be overridden are declared pure virtual. The template method itself should not be overridden; therefore you can make the template method a non virtual member function.


 * **Minimizing primitive operations**. An important goal in designing template methods is to minimize the number of primitive operations that a subclass must override to flesh out the algorithm. The more operations that need overriding, the more tedious things get for clients.


 * Naming conventions. We can identify the operations that should be overridden by adding a prefix to their names.


 * //Example//**

The example below demonstrates "Template Method" pattern implementation. Here, **Transport** is abstract class. **Airplane**, **Boat**, and **Truck** are derived classes from the **Transport** class. The **Transport** class contains "**add_cargo**" function which is a template method. "**add_cargo**" function defines a simple cargo handling algorithm. It also demonstrates the "Hollywood principle", when base class calls operations in derived classes.

code format="cpp" // Module:       template.h // Programmer:    Dmitriy Slipak // Date:       February 22, 2010 // Purpose:       Header file, contains classes declaration //               to illustrate Template Method pattern //
 * Module:** template.h
 * 1) ifndef _TEMPLATE_H_
 * 2) define _TEMPLATE_H_


 * 1) include
 * 2) include

//   set of cargo measurement constants const float MAX_AIRPLANE_CARGO_WIDTH = 200.0; const float MAX_AIRPLANE_CARGO_HEIGHT = 100.0; const float MAX_AIRPLANE_CARGO_WEIGHT = 10000.0;

const float MAX_BOAT_CARGO_WIDTH = 60.0; const float MAX_BOAT_CARGO_HEIGHT = 50.0; const float MAX_BOAT_CARGO_WEIGHT = 5000.0;

const float MAX_TRUCK_CARGO_WIDTH = 20.0; const float MAX_TRUCK_CARGO_HEIGHT = 10.0; const float MAX_TRUCK_CARGO_WEIGHT = 2000.0;

//   cargo structure declaration //   simple structure to handle a cargo struct Cargo {   float width; float height; float weight; };

//   abstract data type Transport declaration class Transport { private: std::vector* trunk;

void load_cargo(Cargo& cargo);   //    primitive operation

protected: void secure_by_fasteners(Cargo& cargo);   //    primitive operation void secure_by_dunnage(Cargo& cargo);   //    primitive operation void secure_by_strap(Cargo& cargo);   //    primitive operation

public: Transport; ~Transport;

void add_cargo(Cargo& cargo);   //    template method virtual bool check_cargo(Cargo& cargo) = 0;   //    primitive operation (hook or placeholder) virtual void secure_cargo(Cargo& cargo) = 0;   //    primitive operation (hook or placeholder) };

//   Airplane class declaration class Airplane : public Transport { public: bool check_cargo(Cargo& cargo);       //    hook or placeholder override void secure_cargo(Cargo& cargo);   //    hook or placeholder override };

//   Boat class declaration class Boat : public Transport { public: bool check_cargo(Cargo& cargo);       //    hook or placeholder override void secure_cargo(Cargo& cargo);   //    hook or placeholder override };

//   Truck class declaration class Truck : public Transport { public: bool check_cargo(Cargo& cargo);       //    hook or placeholder override void secure_cargo(Cargo& cargo);   //    hook or placeholder override };

code
 * 1) endif

code format="cpp" // Module:       template.cpp // Programmer:   Dmitriy Slipak // Date:       February 22, 2010 // Purpose:       Classes implementation file //               to illustrate Template Method pattern //
 * Module:** template.cpp
 * 1) include "template.h"

/// ///   Transport class implementation ///

//   default constructor Transport::Transport {   trunk = new std::vector; };

//   default destructor Transport::~Transport {   delete trunk; }

//   template method, contains a simple cargo handling algorithm //   both, check_cargo and secure_cargo functions calls are examples //   of the "Hollywood principle" void Transport::add_cargo(Cargo& cargo) {   if (!check_cargo(cargo)) {    //    check a cargo measurement ("Hollywood principle") std::cout << "can't handle cargo\n"; return; }

load_cargo(cargo);   //    put a cargo into trunk secure_cargo(cargo);   //    handle a cargo ("Hollywood principle") }

//   primitive operation, no overriding in subclasses void Transport::load_cargo(Cargo& cargo) {   trunk->push_back(cargo); }

//   primitive operation, no overriding in subclasses void Transport::secure_by_fasteners(Cargo& cargo) { std::cout << "the cargo secured by fasteners\n"; } //   primitive operation, no overriding in subclasses void Transport::secure_by_dunnage(Cargo& cargo) { std::cout << "the cargo secured by dunnage\n"; } //   primitive operation, no overriding in subclasses void Transport::secure_by_strap(Cargo& cargo) { std::cout << "the cargo secured by strap\n"; }

/// ///   Airplane class implementation ///

//   Base class primitive operation override bool Airplane::check_cargo(Cargo& cargo) {   if (cargo.height > MAX_AIRPLANE_CARGO_HEIGHT) return false; if (cargo.width > MAX_AIRPLANE_CARGO_WIDTH) return false; if (cargo.weight > MAX_AIRPLANE_CARGO_WEIGHT) return false;

return true; }

//   Base class primitive operation override void Airplane::secure_cargo(Cargo& cargo) {   secure_by_fasteners(cargo);    //    base class primitive operation call }

/// ///   Boat class implementation ///

//   Base class primitive operation override bool Boat::check_cargo(Cargo& cargo) {   if (cargo.height > MAX_BOAT_CARGO_HEIGHT) return false; if (cargo.width > MAX_BOAT_CARGO_WIDTH) return false; if (cargo.weight > MAX_BOAT_CARGO_WEIGHT) return false;

return true; }

//   Base class primitive operation override void Boat::secure_cargo(Cargo& cargo) {   secure_by_dunnage(cargo);    //    base class primitive operation call }

/// ///   Truck class implementation ///

//   Base class primitive operation override bool Truck::check_cargo(Cargo& cargo) {   if (cargo.height > MAX_TRUCK_CARGO_HEIGHT) return false; if (cargo.width > MAX_TRUCK_CARGO_WIDTH) return false; if (cargo.weight > MAX_TRUCK_CARGO_WEIGHT) return false;

return true; }

//   Base class primitive operation override void Truck::secure_cargo(Cargo& cargo) {   secure_by_strap(cargo);    //    base class primitive operation call } code

code format="cpp"
 * Module:** template_driver.cpp
 * 1) include "template.h"

int main {    //    test template method Cargo cargo = {200.0, 100.0, 9000.0};   //    cargo for an airplane

std::cout << "***Airplane\n"; Transport* transport = new Airplane; transport->add_cargo(cargo);   //    template method call delete transport;

//   redefine cargo for a boat cargo.height = 30.0; cargo.width = 40.0; cargo.weight = 2000.0;

std::cout << "\n***Boat\n"; transport = new Boat; transport->add_cargo(cargo);   //    template method call delete transport;

//   redefine cargo for a truck cargo.height = 5.0; cargo.width = 10.0; cargo.weight = 1500.0;

std::cout << "\n***Truck\n"; transport = new Truck; transport->add_cargo(cargo);   //    template method call delete transport;

return 0; } code

Test run produces following result

Complete source code for this example can be located at the course FTP server.

The template method patten is relatively easy in implementation and useful in various situations. This makes the template method pattern as an important addition to software design and development tools set.  =Model-View-Controller Pattern=


 * //Definition//**

Model–View–Controller (MVC) is a software architecture, currently considered as an architectural pattern used in software engineering. The pattern isolates "domain logic" (the application logic for the user) from input and presentation (GUI), permitting independent development, testing and maintenance of each.

The MVC paradigm was originated by Trygve Reenskaug in 1978 during his work at Xerox PARC. The essential purpose of MVC is to bridge the gap between the human user's mental model and the digital model that exists in the computer. The ideal MVC solution supports the user illusion of seeing and manipulating the domain information directly. The structure is useful if the user needs to see the same model element simultaneously in different contexts and/or from different viewpoints. The figure below illustrates the idea.




 * //Classification//**

Object Behavioral Pattern.


 * //Intent//**

The MVC pattern divides an interactive application into three components. The model contains the core functionality and data. Views display information to the user. Controllers handle user input. Views and controllers together comprise the user interface. A change-propagation mechanism ensures consistency between the user interface and the model.


 * //Motivation//**

The Model-View-Controller pattern divides an interactive application into three areas: processing, output, and input. The model component encapsulates core data and functionality. The model is independent of specific output representations or input behavior. View components display information to the user. A view obtains the data from the model. There can be multiple views of the model. Each view has an associated controller component. Controllers receive input, usually as events that encode mouse movement, activation of mouse buttons, or keyboard input. Events are translated to service requests for the model or the view. The user interacts with the system solely through controllers. The separation of the model from view and controller components allows multiple views of the same model. If the user changes the model via the controller of one view all other views dependent o this data should reflect the changes. The model therefore notifies all views whenever its data changes. The views in turn retrieve new data from the model and update the displayed information.


 * //Applicability//**

The MVC pattern might be used:


 * Almost in every application. Depending on the application, some classes might be coupled tighter than others, however it is generally always a good idea to structure an application according to MVC.


 * //Structure//**

The Model-View-Controller pattern structure can be represented by a diagram below.

Here, the solid line represents a direct association, the dashed an indirect association.


 * //Participants//**


 * **Model** - used to manage information and notify observers when that information changes. It contains only data and functionality that are related by a common purpose. If we need to model two groups of unrelated data and functionality, we create two separate models.

> A model encapsulates more than just data and functions that operate on it. A model is meant to serve as a computational approximation or abstraction of some real world process or system. It captures not only the state of a process or system, but how the system works. This makes it very easy to use real-world modeling techniques in defining models.


 * **View** - responsible for mapping graphics onto a device. A view typically has a one to one correspondence with a display surface and knows how to render to it. A view attaches to a model and renders its contents to the display surface. In addition, when the model changes, the view automatically redraws the affected part of the image to reflect those changes. There can be multiple views onto the same model and each of these views can render the contents of the model to a different display surface.

> A view may be a composite view containing several sub-views, which may themselves contain several sub-views.


 * **Controller** - the means by which the user interacts with the application. A controller accepts input from the user and instructs the model and view to perform actions based on that input. In effect, the controller is responsible for mapping end-user action to application response. For example, if the user clicks the mouse button or chooses a menu item, the controller is responsible for determining how the application should respond.


 * //Advantages//**


 * Enhanced maintainability and extensibility of the system.
 * Multiple views of the same model.
 * Plug-gable views and controllers.
 * Code reuse.
 * Synchronized views.


 * //Disadvantages//**


 * Complexity of design and implementation.
 * Data transformation overhead.
 * Observers are unaware of each other - causing problems changing state of the subject potential for excessive number of updates.


 * //Implementation//**

The MVC pattern usually incorporates Observer Pattern and Strategy Pattern.

Classic implementation of the Model-View-Controller pattern consists of three abstract superclasses named Model, View, and Controller, plus numerous concrete subclasses. The abstract classes hold the generic behavior and state of the three parts of MVC. The concrete classes hold the specific state and behavior of the application facilities and user interface components.


 * //Example//**

Here is simple implementation of the MVC pattern. Please note, the example below requires FLTK library.

Note on Building and Using FLTK library
Here are few steps required to be able run the MVC example.


 * 1) Download the FLTK source code. At the moment of this writing stable version is 1.1.10.
 * 2) Compile the fltk source code. I was able successfully compile it under MS Visual C++ 2008 Express Edition using the source located in "vc2005" directory.
 * 3) Copy all the compiled libraries, except "README.lib" from "lib" folder into $(VCInstallDir)\lib (my path is "C:\Program Files\Microsoft Visual Studio 9.0\VC\lib") folder.
 * 4) Copy entire "FL" folder into $(VCInstallDir)\include folder.
 * 5) Edit your project's properties as follows. Go to "Project Properties->Configuration Properties->Linker->Additional Dependencies" and add following libraries: **fltk.lib**, **comctl32.lib**, **wsock32.lib**

The MVC at a first glance seams to be difficult to understand. In fact it is not. There are might be different internal structure for the MVC, ie., it is depends on the application needs how MVC components will access each other and which component is responsible for different updates. Another words, both Controller and View can operate on a Model. Model can be restrictive on the components updates.

The implementation in the example below based on the Observer pattern. Here, the View represents GUI – window, colored pie, and two buttons to increase and decrease the pie in size. Model represents a data holder to keep track of the pie size, and set of members to operate the data. Finally, the Controller represented to operate on the Model, ie., it will change the size of the pie. Simple structure of the example is:

Controller → Model → View

Once user requested to increase or decrease the pie, Controller will change the values of the pie in the Model. Once size of the pie changed in the Model, the Model will send a request to the View. Once, the View received request from the Model for change, the View will update the GUI.

Below is complete source code for the example.

code format="cpp" // Module:       mvc.h // Programmer:    Dmitriy Slipak // Date:       March 02, 2010 // Purpose: //               Header file, //               contains MVC pattern classes declaration //
 * Module:** mvc.h
 * 1) ifndef _MVC_H_
 * 2) define _MVC_H_


 * 1) include
 * 2) include
 * 3) include 
 * 4) include 
 * 5) include 
 * 6) include 

const int PIE_COLOR = 1;   //    red color const int DEFAULT_VIEW_W = 400; const int DEFAULT_VIEW_H = 300; const int PIE_DIAMETER = 120; const int MAX_PIE_W = 200; const int PIE_RESIZE_STEP = 10;

//   Pie class, derived from Fl_Widget struct Pie : public Fl_Widget {   //    Pie ctor, must initialize Fl_Widget Pie(int x, int y, int w, int h) : Fl_Widget(x, y, w, h) { }

void draw; void print_size;

inline int get_x { return x; } inline int get_y { return y; } inline int get_w { return w; } inline int get_h { return h; }

void set_x(const int& value); void set_y(const int& value); void set_w(const int& value); void set_h(const int& value); };

class Subject;

class Observer { public: virtual void update(Subject* s) = 0; };

class Subject { private: std::list observers;

public: void set_message(std::string m);

virtual void subscribe(Observer* o); virtual void unsubscribe(Observer* o); virtual void notify; };

//   Model class, represents simple data holder struct Model : public Subject {   int x;    int y;    int w;    int h;

Model { x = y = w = h = 0; }

inline int get_x { return x; } inline int get_y { return y; } inline int get_w { return w; } inline int get_h { return h; }

void set_x(const int& value); void set_y(const int& value); void set_w(const int& value); void set_h(const int& value); };

class View;   //    View class forward declaration

class Controller : public Observer { private: Model* model; View* view;

protected: std::list subjects;

public: Controller(Model* m); ~Controller;

void subscribe(Subject* s); void unsubscribe(Subject* s); void update(Subject* s);

void increase_pie(const int& value); void decrease_pie(const int& value); };

class View : public Fl_Window, public Observer { private: Model* model; Controller* controller; Fl_Button* btn_plus; Fl_Button* btn_minus; Pie* pie;

inline static void btn_plus_cb(Fl_Widget* widget, void* data) {       ((View*)data)->increase_pie(PIE_RESIZE_STEP); }

inline static void btn_minus_cb(Fl_Widget* widget, void* data) {       ((View*)data)->decrease_pie(PIE_RESIZE_STEP); }

inline void increase_pie(int value) {       controller->increase_pie(PIE_RESIZE_STEP); }

inline void decrease_pie(int value) {       controller->decrease_pie(PIE_RESIZE_STEP); }

protected: std::list subjects;

public: View(int w, int h, const char* t, Model* m, Controller* c); ~View;

inline void activate(Fl_Widget* widget) { widget->activate; } inline void deactivate(Fl_Widget* widget) { widget->deactivate; }

Fl_Widget* get_btn_plus { return btn_plus; } Fl_Widget* get_btn_minus { return btn_minus; }

void run; void subscribe(Subject* s); void unsubscribe(Subject* s); void update(Subject* s); };

code
 * 1) endif

code format="cpp" // Module:       mvc.cpp // Programmer:   Dmitriy Slipak // Date:       March 02, 2010 // Purpose: //               MVC pattern classes implementation //
 * Module:** mvc.cpp
 * 1) include "mvc.h"

/// ///   Subject class implementation /// void Subject::subscribe(Observer* o) { observers.push_back(o); } void Subject::unsubscribe(Observer* o) { observers.remove(o); }

void Subject::notify {   std::list::iterator iter;

for(iter=observers.begin; iter != observers.end; ++iter) ((Observer*)*iter)->update(this); }

/// ///   Pie class implementation ///

//   draw override void Pie::draw {   fl_color(PIE_COLOR); fl_pie(x, y, w, h, 0.0, 360.0); activate; }

void Pie::print_size {   std::cout << "x: " << x << std::endl << "y: " << y << std::endl << "w: " << w << std::endl << "h: " << h << std::endl << std::endl; }

void Pie::set_x(const int& value) { deactivate; x(value); redraw; } void Pie::set_y(const int& value) { deactivate; y(value); redraw; } void Pie::set_w(const int& value) { deactivate; w(value); redraw; } void Pie::set_h(const int& value) { deactivate; h(value); redraw; }

/// ///   Model class implementation /// void Model::set_x(const int& value) { x = value; notify; } void Model::set_y(const int& value) { y = value; notify; } void Model::set_w(const int& value) { w = value; notify; } void Model::set_h(const int& value) { h = value; notify; }

/// ///   Controller class implementation ///

Controller::Controller(Model* m) { model = m;   view = new View(DEFAULT_VIEW_W, DEFAULT_VIEW_H, "MVC", model, this);

subscribe(model); view->run; }

Controller::~Controller {   delete view; }

void Controller::increase_pie(const int& value) {   model->set_x(model->get_x-value/2); model->set_y(model->get_y-value/2); model->set_w(model->get_w+value); model->set_h(model->get_h+value); }

void Controller::decrease_pie(const int& value) {   model->set_x(model->get_x+value/2); model->set_y(model->get_y+value/2); model->set_w(model->get_w-value); model->set_h(model->get_h-value); }

void Controller::subscribe(Subject* s) { subjects.push_back(s); s->subscribe(this); }

void Controller::unsubscribe(Subject* s) { subjects.remove(s); s->unsubscribe(this); }

void Controller::update(Subject* s) { std::list::iterator iter;

for(iter=subjects.begin; iter != subjects.end; ++iter) { if (s != (Subject*)* iter) continue; if (view == 0) break; if (model->get_w <= 0) view->deactivate(view->get_btn_minus); else view->activate(view->get_btn_minus);

if (model->get_w >= MAX_PIE_W) view->deactivate(view->get_btn_plus); else view->activate(view->get_btn_plus); } }

/// ///   View class implementation ///

View::View(int w, int h, const char* t, Model* m, Controller* c) : Fl_Window(w, h, t) { model = m;   controller = c;    subscribe(model);

btn_plus = new Fl_Button(w/2-35, 10, 30, 20, "+"); btn_minus = new Fl_Button(w/2+5, 10, 30, 20, "-"); pie = new Pie(model->get_x, model->get_y, model->get_w, model->get_h);

//   initialize model, set default size model->set_x(w/2-PIE_DIAMETER/2); model->set_y(h/2-PIE_DIAMETER/2); model->set_w(PIE_DIAMETER); model->set_h(PIE_DIAMETER);

end;   //    end of controls placed on FLTK window

//   initialize callback functions for buttons btn_plus->callback(btn_plus_cb, (void*) this); btn_minus->callback(btn_minus_cb, (void*) this); }

View::~View {   delete btn_plus; delete btn_minus; delete pie; }

void View::run {   show;    //    activate window while (Fl::wait);   //    display window until closed }

void View::subscribe(Subject* s) { subjects.push_back(s); s->subscribe(this); }

void View::unsubscribe(Subject* s) { subjects.remove(s); s->unsubscribe(this); }

void View::update(Subject* s) { std::list::iterator iter;

for(iter=subjects.begin; iter != subjects.end; ++iter) { if (s != (Subject*)* iter) continue;

pie->set_x(model->get_x); pie->set_y(model->get_y); pie->set_w(model->get_w); pie->set_h(model->get_h); pie->print_size; } } code

code format="cpp"
 * Module:** mvc_driver.cpp
 * 1) include "mvc.h"

int main {   Model* model = new Model; Controller* controller = new Controller(model); delete controller; delete model;

return 0; } code

You can watch below the sample run of the example. Complete source code for this example can be located at the course FTP server.

media type="youtube" key="pnLdBTeGFq0" width="480" height="400"  =Mixed Patterns=

We combined implementation of the State pattern and Model-View-Controller pattern in the example below. Here, State pattern is responsible for state changes in the program, and MVC pattern is responsible for GUI updates.

code format="cpp"
 * Module:** mvc.h
 * 1) ifndef _MVC_H_
 * 2) define _MVC_H_


 * 1) include
 * 2) include
 * 3) include 
 * 4) include 
 * 5) include 
 * 6) include <FL/Fl_draw.h>

const int PIE_NUM = 3;

const enum PIE_COLOR { COLOR_RED=1, COLOR_YELLOW=3, COLOR_GREEN=2, COLOR_GREY=8 };

const enum STATE { STOP=0, GO=1, WAIT=2

};

const int DEFAULT_VIEW_W = 350; const int DEFAULT_VIEW_H = 600; const int PIE_DIAMETER = 150; const int MAX_PIE_W = 150;

//   Pie class, derived from Fl_Widget struct Pie : public Fl_Widget {   int id;

Pie(int x, int y, int w, int h, int pie_id) : Fl_Widget(x, y, w, h) { id = pie_id; }

void draw; };

class Subject;

class Observer { public: virtual void update(Subject* s) = 0; };

class Subject { private: std::list<Observer*> observers;

public: void set_message(std::string m);

virtual void subscribe(Observer* o); virtual void unsubscribe(Observer* o); virtual void notify; };

//   Model class, represents simple data holder struct Model : public Subject {   STATE state;

Model { state = STOP; }

inline int get_state { return state; }

inline void set_state(STATE value) { state = value; notify; } };

class View;   //    View class forward declaration

class Controller : public Observer { private: Model* model; View* view;

protected: std::list<Subject*> subjects;

public: Controller(Model* m); ~Controller;

void subscribe(Subject* s); void unsubscribe(Subject* s); void update(Subject* s) {};

void get_input(const int& value); };

class View : public Fl_Window, public Observer { private: Model* model; Controller* controller; std::list<Pie*> pie_list;

protected: std::list<Subject*> subjects;

public: View(int w, int h, const char* t, Model* m, Controller* c); ~View;

void run; void subscribe(Subject* s); void unsubscribe(Subject* s); void update(Subject* s); };

code
 * 1) endif

code format="cpp"
 * Module:** mvc.cpp
 * 1) include "mvc.h"

/// ///   Subject class implementation /// void Subject::subscribe(Observer* o) { observers.push_back(o); } void Subject::unsubscribe(Observer* o) { observers.remove(o); }

void Subject::notify {   std::list<Observer*>::iterator iter;

for(iter=observers.begin; iter != observers.end; ++iter) ((Observer*)*iter)->update(this); }

/// ///   Pie class implementation ///

//   draw override void Pie::draw {   fl_color(color); fl_pie(x, y, w, h, 0.0, 360.0); activate; }

/// ///   Controller class implementation ///

Controller::Controller(Model* m) { model = m;   view = new View(DEFAULT_VIEW_W,        DEFAULT_VIEW_H,        "State Pattern Example",        model,        this);

subscribe(model); model->set_state(STOP); view->run; }

Controller::~Controller {   delete view; }

void Controller::subscribe(Subject* s) { subjects.push_back(s); s->subscribe(this); }

void Controller::unsubscribe(Subject* s) { subjects.remove(s); s->unsubscribe(this); }

void Controller::get_input(const int& value) {   model->set_state((STATE)value); }

/// ///   View class implementation ///

View::View(int w, int h, const char* t, Model* m, Controller* c) : Fl_Window(w, h, t) { model = m;   controller = c;    subscribe(model);

int y = 0; for (int i = 0; i < PIE_NUM; i++) { switch (i) { case 0: y = (h/2-PIE_DIAMETER/2)-200; break; case 1: y = h/2-PIE_DIAMETER/2; break; case 2: y = (h/2-PIE_DIAMETER/2)+200; break; default: break; }

pie_list.push_back(new Pie(w/2-PIE_DIAMETER/2, y,           PIE_DIAMETER, PIE_DIAMETER, i)); }

end;   //    end of controls placed on FLTK window }

View::~View {   pie_list.clear; }

void View::run {   show;    //    activate window }

void View::subscribe(Subject* s) { subjects.push_back(s); s->subscribe(this); }

void View::unsubscribe(Subject* s) { subjects.remove(s); s->unsubscribe(this); }

void View::update(Subject* s) { std::list<Subject*>::iterator iter; std::list<Pie*>::iterator pie_iter;

for(iter = subjects.begin; iter != subjects.end; ++iter) {       for(pie_iter = pie_list.begin; pie_iter != pie_list.end; ++pie_iter) { switch (model->get_state) { case STOP: if (((Pie*)*pie_iter)->id == 0) ((Pie*)*pie_iter)->color(COLOR_RED); else ((Pie*)*pie_iter)->color(COLOR_GREY); break; case WAIT: if (((Pie*)*pie_iter)->id == 1) ((Pie*)*pie_iter)->color(COLOR_YELLOW); else ((Pie*)*pie_iter)->color(COLOR_GREY); break; case GO: if (((Pie*)*pie_iter)->id == 2) ((Pie*)*pie_iter)->color(COLOR_GREEN); else ((Pie*)*pie_iter)->color(COLOR_GREY); break; }       }    }

redraw; } code

code format="cpp"
 * Module:** mvc_driver.cpp
 * 1) include <time.h>
 * 2) include
 * 3) include "mvc.h"

using namespace std;

class Signal {   Model* model; Controller* controller; class State *current; public: Signal; ~Signal;

void setCurrent(State *s) {               current = s;            }

void green; void yellow; void red; };

class State {   public: virtual void green(Signal *m) {           cout << "   already GREEN" << endl; }

virtual void red(Signal *m) {           cout << "   already RED" << endl; }

virtual void yellow(Signal *m) {           cout << "   already YELLOW" << endl; } };

void Signal::green {   current->green(this); controller->get_input(GO); }

void Signal::red {   current->red(this); controller->get_input(STOP); }

void Signal::yellow {   current->yellow(this); controller->get_input(WAIT); }

class GREEN: public State {   public: void yellow(Signal *m); };

class YELLOW: public State {   public: void red(Signal *m); };

class RED: public State {   public: void green(Signal *m) {           cout << "   going from RED to GREEN" << endl; m->setCurrent(new GREEN); delete this; } };

void GREEN::yellow(Signal *m) {   cout << "   going from GREEN to YELLOW" << endl; m->setCurrent(new YELLOW); delete this; }

void YELLOW::red(Signal *m) {   cout << "   going from YELLOW to RED" << endl; m->setCurrent(new RED); delete this; }

Signal::Signal {   model = new Model; controller = new Controller(model); current = new RED; cout << endl; }

Signal::~Signal {   delete model; delete controller; delete current; }

void delay(const int& interval) {   int seconds = clock; while (seconds + interval >= clock); }

int main {   void(Signal:: *ptrs[]) = {       &Signal::red, &Signal::green, &Signal::yellow };

Signal fsm; int i = 0;

while (Fl::wait) { (fsm.*ptrs[i]); i++; delay(2000); if (i >= 3) i = 0; }

system("Pause"); return 0; } code

Complete source code for this example can be found at course FTP server.

You can watch the output result below.

media type="youtube" key="kQP7ANvDaRo" width="480" height="400"  =7. Conclusion=

I found this particular project exciting. The library Dmitiry discovered to ease the development of a GUI in C++ was a nice find. I have yet to delve too much into that particular tool, again another area of future research on my part. I can see the need for the use of this pattern in some of the areas we are working in; now to convince the rest do the folks design patterns are useful! Even though each of the patterns describe were easy to implement; that doesn't mean that they are not powerful tools in a developer's arsenal.

All the four patterns represented in this project are good additions to the application design/development tool set. Each of the patterns demonstrates a particular way for different problems to be solved. The MVC pattern is extremely useful for applications with GUI involved. Most important aspect of the MVC is that the pattern itself helps an application to be well organized and structured. The State-MVC combination project is especially interesting since it demonstrates wide range of patterns abilities.  =8. References=


 * 1) The Gang of Four (GoF) book //(Design Patterns: Elements of Reusable Object-Oriented Software, 1995, Pearson Education, Inc. Publishing as Pearson Addison Wesley//
 * 2) Holzner, Steve PhD, “Design Patterns For Dummies”, Wiley Publishing, Inc., Hoboken, NJ, 2006
 * 3) Gamma, Eric, et al, "Design Patterns" Addison-Wesley Publishing, August 1997
 * 4) State Pattern, http://en.wikipedia.org/wiki/State_pattern, Accessed April 2010
 * 5) Proxy Pttern, http://en.wikipedia.org/wiki/Proxy_pattern, Accessed April 2010
 * 6) The original MVC reports. Trygve Reenskaug - 1979.
 * 7) MVC article from Wikipedia.
 * 8) Head First Design Patterns by Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates. 2004 - O'Reilly Media, Inc.

Last revision date: {$revisiondate}