SSE658+Project3+Nguyen-Patel

Template Method Pattern defines skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method let subclasses redefines certain steps of an algorithm without changing the algorithm’s structure. [Freeman, page. 289] This pattern is about creating a template for an algorithm. This template is just a method, defined in an abstract class. The template method contains a collection of steps where each step could be abstract or non-abstract methods. It manages the larger picture of task semantics, and the detail selection and sequence of methods. Non-abstract methods are completed control by the Template method while abstract methods are subject to be implemented by subclass. This allows differing behavior while ensuring algorithm’s structure stays the same.
 * The Template Method Pattern **

**
 * Template Method UML class diagram


 * Code Implementation of Template Method Pattern**

__**Abstract class:**__

/// // / Abstract class /// public abstract class cookieShopTemplate {// Template method public string MakeCookie { StringBuilder cookie = new StringBuilder ; cookie.Append( "\n\nMaking your cookie..............\n" ); cookie.Append(mixWaterSugar);

if (wantFlavor){ cookie.Append(addFlavor); }

cookie.Append(cookieShape); cookie.Append(bake); cookie.Append( "DONE!!!! Here is your cookie. Enjoy!!!!!!" ); return cookie.ToString; }

//abstract methods: to be implement by subsclass public abstract string cookieShape; public abstract string addFlavor;//

non-abstract method string mixWaterSugar { return "Mix water and sugar\n" ; }

string bake { return "Bake cookie\n" ; }

//hook method public virtual bool wantFlavor { return false ; } } The code above is the definition of an abstract class name “cookieShopTemplate”. This class contain a template method name “MakeCookie” that defining the process(algorithm) of making a cookie. The definition of none-abstract methods “mixWaterSugar, bake” are defined in this abstract class while abstract methods “cookieShape, addFlavor” are left for subclass to implement. There is also a hook method “wantFlavor”. Hook methods are optional. They are declared in the abstract class with empty or default implementation. They are subject to be overridden in subclass as needed. This gives the subclass the ability to hook into the algorithm at various points if desire or subclass can just ignore the hook method. The “wanFlavor”’s default behavior is to do nothing.

__**Concrete class**__// / ///// //Concrete class that extent the abstract cookieShopTemplate class// / public class Cookie : cookieShopTemplate { //default constructor public Cookie { }//

implement abstract method that declared in the abstract class public override string cookieShape { Console .WriteLine( "Round or Square cookie?" ); string response = Console .ReadLine; return response+ " the cookies\n" ; }

//implement abstract method that declared in the abstract class// this behavoir only add through hook method public override string addFlavor { Console .WriteLine( "Which flavor do you want? \nMint \ncremes \nlemon \nchocolate" ); string response = Console .ReadLine; return "add" + response+ "\n" ; }

//override hook method defined in the abstract class with// appropriate behavoir public override bool wantFlavor { Console .WriteLine( "Do you want to add any flavor to the cookie? y/n" ); string response = Console .ReadLine; if (response == "y" ) { return true ; } else { return false ; } } } Above codes define concrete class that extents the abstract class. It implements abstract methods declared in the abstract class to provide specific behaviors. It also takes advantage of the hook method to provide additional behavior “addFlavor”.

__**Test drive Template Method.**__ class MakeCookie { static void Main( string [] args) { Cookie sampleCookie = new Cookie ; Console .WriteLine( "Welcome to cookie factory!!!!!!!!" ); Console .WriteLine(sampleCookie.MakeCookie); Console .ReadLine; } }

__**Output**__ The State Pattern ** State Pattern is a behavior pattern. This pattern is used to represent the state of an object. It allows an object to alter its behavior when its internal state changes. The object will appear to change its class. [Freeman, page. 410] The state pattern defines each state as separate classes. Depending on the current state, it delegates to the object represent that state to perform operation. Class that represents a state encapsulates a set of behaviors that associate with that state.

** While state pattern and strategy pattern are similar and their UML class diagrams are almost the same, they are differ in their intent. State pattern encapsulates state-based behavior and delegate behavior to the current state, while strategy pattern encapsulates interchangeable behaviors and use delegation to decide which behavior to use.
 * State Pattern UML class diagram
 * State Pattern vs. Strategy Pattern**

The codes below describe the states and the processes of a pump at the gas station.
 * Code Implementation of State Pattern**

__**Interface:**__ //class interface. All state class must implement this interface public interface QuixPumpState {// interface method string insertCreditCard; string cancel; string startThePump; string dispenseGas; } This defines state interface for state classes

__**State classes:**__ //Waiting state class public class waitingState : QuixPumpState {// class attributes QuixPump PumpStation; //construtor public waitingState( QuixPump Pump) { this .PumpStation = Pump; }//

implement state behavior public string insertCreditCard { this .PumpStation.currentState = this .PumpStation.getPaidState; return "I love money. Please wait a moment......" ; }

public string cancel { return "You wanna cancel? You never put your credit card in." ; }

public string startThePump { return "So, You wanna start the pump. Pay me 1st" ; }

public string dispenseGas { return "\nOh, you wanna steal my Gas." ; } }

//Paid state class public class paidState : QuixPumpState {// class attributes QuixPump PumpStation;

//constructor public paidState( QuixPump Pump) { this .PumpStation = Pump; }//

implement state behavior public string insertCreditCard { return "You wanna pay me again? I like you." ; }

public string cancel { this .PumpStation.currentState = this .PumpStation.getWaitingState; return "AHHHHHH. You cancelled." ; }

public string startThePump { this .PumpStation.currentState = this .PumpStation.getFilledState; return "The pump started" ; }

public string dispenseGas { return "No Gas dispense yet." ; } }

//Filled state class public class filledState : QuixPumpState {// class attributes QuixPump PumpStation;

//constructor public filledState( QuixPump Pump) { this .PumpStation = Pump; }// implement state behavior public string insertCreditCard { return "You already paid. Gas is dispensing now." ; }

public string cancel { return "You can't cancel now. You must stop the pump 1st." ; }

public string startThePump { return "The pump already started." ; }

public string dispenseGas { //Pump Gas into customer car this .PumpStation.releaseGas;// check pump status to set appropriate state if ( this .PumpStation.currentTankStatus > 0) { this .PumpStation.currentState = this .PumpStation.getWaitingState; return "\nFinished pumping gas. Thank you" ; } else { this .PumpStation.currentState = this .PumpStation.getEmptiedState; return "\nYou emptied my tank. Thank you" ; } } }

//Emptied state class public class emptiedState : QuixPumpState {// constructor public emptiedState {} //implement state behavior public string insertCreditCard { return "We sold out. Come back later" ; }

public string cancel { return "Errrrr... Cancel What?" ; }

public string startThePump { return "Go ahead and start the pump but nothign gonna happen" ; }

public string dispenseGas { return "Sorry, i'm out of gas" ; } }

The above is sample codes of four states of the Pump Station. Each state class implements each method differently. State classes provide appropriate behaviors corresponding to the state of the Pump Station.

__**Context class:**__// Context class public class QuixPump { //class attributes QuixPumpState waitingState; QuixPumpState paidState; QuixPumpState filledState; QuixPumpState emptiedState; QuixPumpState PumpState; int Gallon = 0;// properties public QuixPumpState currentState { get { return PumpState; } set { this .PumpState = value ;} }

public int currentTankStatus { get { return this .Gallon; } }

//construtor public QuixPump( int gal) { waitingState = new waitingState ( this ); paidState = new paidState ( this ); filledState = new filledState ( this ); emptiedState = new emptiedState ; this .Gallon = gal; if ( this .Gallon > 0) { this .currentState = waitingState; } else { this .currentState = emptiedState; } }

public string insertCreditCard { return PumpState.insertCreditCard; }

public string cancel { return PumpState.cancel; }

public string startThePump { return PumpState.startThePump + PumpState.dispenseGas; }// Fill QuixPump's gas tank public string reFillTank( int gal) { this .Gallon += gal; if ( this .Gallon > 0) { this .currentState = waitingState; } else { this .currentState = emptiedState; } return "\nThe Tank is refilled. \nCurrent Status is " + this .Gallon + " gallons" ; }

//Pump gas to customer car public void releaseGas { this .Gallon -= 1; }

public QuixPumpState getWaitingState { return waitingState; }

public QuixPumpState getPaidState { return paidState; }

public QuixPumpState getFilledState { return filledState; }

public QuixPumpState getEmptiedState { return emptiedState; } }

Depending on the current state of the Pump, the context class delegates the appropriate state class to provide corresponding action. Every action that took place in the state classes might result in changing the state of the Pump.

__**Client (Test drive QuixPump)**__ class QuixPumTrialRun { static void Main( string [] args) { QuixPump PumpA = new QuixPump (1);

Console .WriteLine( "Pump A status: " + PumpA.currentState);

Console .WriteLine( "\nNEW TRANSACTION!!!!!!!!!!!!!" ); Console .WriteLine(PumpA.insertCreditCard); Console .WriteLine(PumpA.startThePump);

Console .WriteLine( "\nNEW TRANSACTION!!!!!!!!!!!!!" ); Console .WriteLine(PumpA.insertCreditCard);

Console .WriteLine(PumpA.reFillTank(10));

Console .WriteLine( "\nNEW TRANSACTION!!!!!!!!!!!!!" ); Console .WriteLine(PumpA.insertCreditCard); Console .WriteLine(PumpA.cancel); Console .WriteLine(PumpA.startThePump);

Console .WriteLine( "\nNEW TRANSACTION!!!!!!!!!!!!!" ); Console .WriteLine(PumpA.cancel); Console .WriteLine(PumpA.startThePump);

} }

__**Result:**__

State pattern puts all behaviors associate with a state into one object. It allows transition of state logic to be incorporated into state object rather than switch statement.
 * Benefit of State Pattern**

Iterator Pattern is one that allows us to navigate through a collection of data using a common interface without knowing its underlying implementation. Iterator Pattern should be implemented as interface. This allows every user to implement it in the manner that most likely suits the requirement. The Iterator pattern mainly relies on an interface called Iterator. This interface can then be implement for any kind of collection of objects: arrays, lists, hash tables, and ect.
 * The Iterator Pattern **

**
 * Iterator Pattern UML class diagram

The codes below describe the Iterator method and the processes of remote controls. When channel up, down, and back key press the remote iterate through the channels.
 * Code Implementation of Iterator Pattern**

public interface Iterator { public Channel nextChannel(int currentChannel); public Channel previousChannel(int currentChannel); } The Channel iterator is common for all the remote controls. It’s like a specification implemented by all the remote control. public ChannelSurfer implements Iterator { public Channel nextChannel(int currentChannel) { Channel channel=new Channel(currentChannel+1); return channel; } public Channel previousChannel(int currentChannel) { Channel channel=new Channel(currentChannel-1); return channel; } } public class RemoteControl { private ChannelSurfer surfer; public RemoteControl { surfer=new ChannelSurfer; } public Program getProgram(ChannelSurfer surfer) { return new Program(surfer.nextChannel); } } public Program {// ... Some specific implementation of Program class. }

Iterator pattern can be use to support traversals of many objects without exposing their internal representation. It is also support to provide a uniform interface for traversing different aggregate structures.
 * Benefit of Iterator Pattern**

A Composite is a tree structure consisting of individual objects mixed with compositions of objects. The goal of the Composite pattern is to be able to treat individual objects and compositions of objects the same way. All objects in the Composite are derived from Composite itself. The key to a composite pattern is an abstract class that represents both individual objects and their compositions of objects. Define Component that specifies the behavior that needs to be exercised uniformly across all primitive and composite objects. Subclass the Primitive and Composite classes off of the Component class. Each Composite object connects itself only to the abstract type Component as it manages its children.
 * The Composite Pattern **

**
 * Composite Pattern UML class diagram
 * Component** - Component is the abstraction for leafs and composites. It defines the interface that must be implemented by the objects in the composition.
 * Leaf** - Leafs are objects that have no children. They implement services described by the Component interface.
 * Composite** - A Composite stores child components in addition to implementing methods defined by the component interface. Composites implement methods defined in the Component interface by delegating to child components.
 * Client** - The client manipulates objects in the hierarchy using the component interface.

The code below demonstrates the Composite pattern, which allows the creation of a tree structure in which individual nodes are accessed uniformly whether they are leaf nodes or branch (composite) nodes. class MainApp { static void Main { //Create a tree structure Composite root = new Composite("root"); root.Add(new Leaf("Leaf A")); root.Add(new Leaf("Leaf B")); Composite comp = new Composite("Composite X"); comp.Add(new Leaf("Leaf XA")); comp.Add(new Leaf("Leaf XB")); root.Add(comp); root.Add(new Leaf("Leaf C"));// Add and remove a leaf Leaf leaf = new Leaf("Leaf D"); root.Add(leaf); root.Remove(leaf); //Recursively display tree root.Display(1);// Wait for user Console.ReadKey; } } /// The 'Component' abstract class abstract class Component { protected string name; public Component(string name){ this.name = name; } public abstract void Add(Component c); public abstract void Remove(Component c); public abstract void Display(int depth); }// / The 'Composite' class class Composite : Component { private List _children = new List; public Composite(string name):base(name){ } public override void Add(Component component) { _children.Add(component); } public override void Remove(Component component) { _children.Remove(component); } public override void Display(int depth) { Console.WriteLine(new String('-', depth) + name); foreach (Component component in _children){ component.Display(depth + 2); } } } /// The 'Leaf' class class Leaf : Component { public Leaf(string name)
 * Code Implementation of Composite Pattern**
 * base(name){

} public override void Add(Component c) { Console.WriteLine("Cannot add to a leaf"); } public override void Remove(Component c) { Console.WriteLine("Cannot remove from a leaf"); } public override void Display(int depth) { Console.WriteLine(new String('-', depth) + name); } } }

The composite pattern defines class hierarchies consisting of primitive objects and composite objects. Primitive objects can be composed into more complex objects, which in turn can be composed. Clients treat primitive and composite objects uniformly through a component interface that makes client code simple. Adding new components can be easy and client code does not need to be changed since client deals with the new components through the component interface.
 * Benefit of Composite Pattern**