Erickson-Lynch-SSE658-Project3

toc Project 3 SSE 658 - Design Problems and Solutions by Paul Erickson and Brandon Lynch For Dr. Paul E. Macneil =Introduction= Paul Erickson and Brandon Lynch have partnered up to showcase topics discussed in the Head First Design Pattern's Book. The topics will cover everything in chapters 8-13 of the book.

=State Pattern=

The state pattern is a behavioral software design pattern that identifies communication patterns between objects and realizes these patterns. This type of pattern increases the flexibility in carrying out the pattern. Here are the important aspects of the state pattern:
 * The objects internal state allows for many different behaviors.
 * This pattern represents state as a class.

Gear Shifter Program
Here, I have created a diagram that represents a car gear shifter. The driver of the vehicle can either shift the gear up or down to a certain point. Park is the top most gear and 1st gear is the bottom most gear. There are 6 states that most cars can be in. These are:
 * 1) Park
 * 2) Reverse
 * 3) Neutral
 * 4) Drive
 * 5) 2nd Gear
 * 6) 1st Gear



First, I create an interface that all gear states will inherit. There are two methods that change the state of the gear: ChangeGearUp and ChangeGearDown. ChangeGearUp will change the gear state in the upwards direction and ChangeGearDown will change the gear state in the downwards direction. code format="csharp" using System;

namespace CarStatePattern {   interface GearState {       void ChangeGearDown; void ChangeGearUp; } }

code

Next, I have 5 states that inherit the CarStatePattern interface. The contructor will pass in the current car shifter class. The ChangeGearUp and ChangeGearDown methods will move the gear in the proper direction.

Park State
code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace CarStatePattern {   class ParkState : GearState {       CarShifter carshifter = null; public ParkState(CarShifter shifter) {           this.carshifter = shifter; }

#region GearState Members

public void ChangeGearDown {           Console.WriteLine("Gear changing to Reverse."); this.carshifter.SetState(this.carshifter.ReverseState); }

public void ChangeGearUp {           Console.WriteLine("*******Gear cannot be moved up*****"); }

#endregion

public override string ToString {           return "Park Gear"; }   } } code

Reverse State
code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace CarStatePattern {   class ReverseState : GearState {       CarShifter carshifter = null; public ReverseState(CarShifter shifter) {           this.carshifter = shifter; }

#region GearState Members

public void ChangeGearDown {           Console.WriteLine("...Gear changing to Neutral Gear"); this.carshifter.SetState(this.carshifter.NeutralState); }

public void ChangeGearUp {           Console.WriteLine("...Gear changing to Park Gear"); this.carshifter.SetState(this.carshifter.ParkState); }

#endregion

public override string ToString {           return "Reverse Gear"; }   } } code

Neutral State
code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace CarStatePattern {   class NeutralState : GearState {       CarShifter carshifter = null; public NeutralState(CarShifter shifter) {           this.carshifter = shifter; }

#region GearState Members

public void ChangeGearDown {           Console.WriteLine("...Gear changing to Drive."); this.carshifter.SetState(this.carshifter.DriveState);

}

public void ChangeGearUp {           Console.WriteLine("...Gear changing to Park."); this.carshifter.SetState(this.carshifter.ParkState); }

#endregion

public override string ToString {           return "Neutral Gear"; }   } } code

Drive State
code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace CarStatePattern {   class DriveState : GearState {       CarShifter carshifter = null; public DriveState(CarShifter shifter) {           this.carshifter = shifter; }

#region GearState Members

public void ChangeGearDown {           Console.WriteLine("...Gear changing to 2nd Gear"); this.carshifter.SetState(this.carshifter.SecondGearState); }

public void ChangeGearUp {           Console.WriteLine("...Gear changing to Neutral Gear"); this.carshifter.SetState(this.carshifter.NeutralState); }

#endregion

public override string ToString {           return "Drive Gear"; }   } } code

Second Gear State
code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace CarStatePattern {   class SecondGearState : GearState {       CarShifter carshifter = null; public SecondGearState(CarShifter shifter) {           this.carshifter = shifter; }

#region GearState Members

public void ChangeGearDown {           Console.WriteLine("...Gear changing to First Gear"); this.carshifter.SetState(this.carshifter.FirstGearState); }

public void ChangeGearUp {           Console.WriteLine("...Gear changing to Drive Gear"); this.carshifter.SetState(this.carshifter.DriveState); }

#endregion

public override string ToString {           return "2nd Gear"; }   } } code

First Gear State
code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace CarStatePattern {   class FirstGearState : GearState {       CarShifter carshifter = null; public FirstGearState(CarShifter shifter) {           this.carshifter = shifter; }

#region GearState Members

public void ChangeGearDown {           Console.WriteLine("*******GEAR CANNOT BE MOVED DOWN*****"); }

public void ChangeGearUp {           Console.WriteLine("...Gear changing to 2nd Gear"); carshifter.SetState(this.carshifter.SecondGearState); }

#endregion

public override string ToString {           return "1st Gear"; }   } } code

Car Shifter
Now, I have created a Car Shifter class. In the constructor I create and instance of each state. The states act as a wrapper around this object, where the class is passed into another class and manipulated by it. There are specific properties for the carshifter such as its current state and each created state. Also, you set the gear state using the SetState method. code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace CarStatePattern {   class CarShifter {       private GearState parkState = null; private GearState reverseState = null; private GearState neutralState = null; private GearState driveState = null; private GearState secondGearState = null; private GearState firstGearState = null;

GearState state = null;

public CarShifter {           parkState = new ParkState(this); reverseState = new ReverseState(this); neutralState = new NeutralState(this); driveState = new DriveState(this); secondGearState = new SecondGearState(this); firstGearState = new FirstGearState(this);

State = this.ParkState; }

internal GearState State {           get { return state; } set { state = value; } }

internal GearState ParkState {           get {               Console.WriteLine("///////////Gear Now in Park////////////////"); return parkState; }       }

internal GearState ReverseState {           get {               Console.WriteLine("///////////Gear Now in Reverse////////////////"); return reverseState; }       }

internal GearState NeutralState {           get {               Console.WriteLine("///////////Gear Now in Neutral////////////////"); return neutralState; }       }

internal GearState DriveState {           get {               Console.WriteLine("///////////Gear Now in Drive////////////////"); return driveState; }       }

internal GearState SecondGearState {           get {               Console.WriteLine("///////////Gear Now in 2nd Gear////////////////"); return secondGearState; }       }

internal GearState FirstGearState {           get {               Console.WriteLine("///////////Gear Now in 1st Gear////////////////"); return firstGearState; }       }

public void SetState(GearState state) {           this.state = state; }

public void ChangeGearDown {           state.ChangeGearDown; }

public void ChangeGearUp {           state.ChangeGearUp; }   } } code

Final Program Class
code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace CarStatePattern {   class Program {

static void Main(string[] args) {           ConsoleKeyInfo ck; CarShifter shift = null; bool caron = false; Console.WriteLine("Turn Ignition to Start Car.               (press E key to turn car on. Press Escape to quit)");

ck = Console.ReadKey(true);

while (ck.Key != ConsoleKey.Escape) {               if (ck.Key == ConsoleKey.E && !caron) {                   Console.WriteLine("Car Started"); shift = new CarShifter; caron = true; ck = Console.ReadKey(true); }               else {                   ck = Console.ReadKey(true); }

if (ck.Key == ConsoleKey.E && caron && shift.State.ToString == "Park Gear") {                   Console.WriteLine("Car Turned Off"); caron = false; ck = Console.ReadKey(true); }

if (ck.Key == ConsoleKey.E && caron && shift.State.ToString != "Park Gear") {                   Console.WriteLine("Car is currently on: " + shift.State.ToString +            ". Car Must Be In Park to Turn it Off!"); }

if (!caron) {                   Console.WriteLine("Car not turned on!"); }

if (ck.Key == ConsoleKey.UpArrow && caron) {                   shift.ChangeGearUp; }

if (ck.Key == ConsoleKey.DownArrow && caron) {                   shift.ChangeGearDown; }

}

}   } } code

Finally, I created the main class which will create a console application. Here, I made a little game out of this pattern. First, you have to press "E" to turn the car engine on. After you turn the car on the car shifter's initial state is "PARK". Now, you can shift the gear into any state by pressing the up and down arrows, just like a gear shifter in a car. When you do this a message will display letting you know what gear you shifted too. To turn the engine of you can press "E" again. However, you must be in the park state to turn the car off. Below is a picture of the console application in action:



Good Things About my use of this pattern:
The state pattern solves many issues with code maintenance. As you can see in my pattern, I could create a virtual car with more gear shifts. Each new gear shift would only have to implement the interface and added to the Car Shifter class. Also, if I need to change any functionality with a certain gear I would only have to do it in the gears state class and the functionality would be picked up by the Final Program class that shifts the gears.

Not so good about my use of this pattern:
The state pattern creates a lot of small classes. I would have to make sure I organize them well. Other than that I believe this pattern has made it possible to quickly develop a gear shift system in a car.

Click the file below to download the project files



=Proxy Pattern=

The proxy pattern is a structural pattern in which it is used to form large object structures across many disparate objects. This pattern defines a proxy object that acts between a client and a real subject to control access to the real subject and to perform necessary tasks every time the real subject is accessed. Since head first is JAVA based they talk about how Java’s RMI service uses this pattern to communicate remotely using a proxy object. However, I will talk about .NET’s WCF (Windows Communication Foundation) since it is more in line to the current and future work environments that I will be part of.

There are different types of ways to use the proxy pattern, which include:
 * Virtual Proxies – creates large expensive objects on demand.
 * Remote Proxies - a local representation of a real subject in a different address space such as a remote object on another host.
 * Protection Proxies – grant or deny the client access to the real subject.
 * Smart References – extend the functionality of “simple” pointers and perform additional maintenance actions every time the real subject is accessed.

Windows Communication Foundation
WCF enables applications to communicate whether they are on the same computer, across the internet, or on different platforms. WCF contains four elements:
 * 1) Contract Definition – A service must have at least one service contract.
 * 2) Endpoint Definitions – One or more address-binding-contract endpoints must be declared.
 * 3) Hosting Code – Some code is needed to create and start the service.
 * 4) Implementation Code – Service contracts in a service need code to implement the service operations.

WCF Contracts
These contracts allow clients and services to have a common understanding of available operations, data structures, and messaging structures while remaining loosely coupled and platform independent. There are four kinds of contracts:
 * 1) Service Contracts – Contracts that define what a contract can do. In WCF these are defined with [ServiceContract] and [OperationContract] attributes. [Binding Requirements] will specify binding requirements for the contract.
 * 2) Data Contract – Defines a data structure using [DataContract] and [DataMemeber] attributes.
 * 3) Message Contract – Defines what goes where in a message. This is defined by the [MessageContract], [MessageBodyMember], and [MessageHeader].
 * 4) Fault Contract – Documents the errors that the WCF code produces. This uses the [FaultContract] attribute.

EndPoints
Each endpoint consists of an address, a binding, and a contract. Services expose these endpoints in which messages can be sent.
 * Address – Defines where to send messages.
 * Binding – Defines how to send messages.
 * Contract – Defines what the message contains.

Client need to know this information in order to access this information.

Hosting
There are several ways you can host a WCF Service:
 * IIS (Internet Information Service) – Uses HTTP as its transport. IIS does not require you to have to write any hosting code because IIS activates service code as required. To run this service, create service code along with its configuration file and save them to the IIS virtual directory.
 * WAS - this is a new process activation mechanism in IIS 7.0. The process and hosting models are no longer dependent on HTTP. WCF can use WAS to provide message based activation over other protocols, such as TCP and named pipes. WCF can now take advantage of WAS features such as process recycling, rapid fail protection, and the common configuration system.
 * Self-Hosting – WCF hosting can be managed inside of a windows forms or WPF application.
 * Managed Windows Service – WCF can be registered as a Windows Service so it is under control of the Service Control Manager.

Implementation
It is important to implement the design using a particular lifecycle:
 * 1) Define the service contract
 * 2) Implement the contract
 * 3) Configure the service by specifying endpoint information and other behavior info.
 * 4) Build a client application.

Rental Service Application
My application will be a movie rental service. You will be able to rent and return movies remotely. First, I will need to create a WCF Library project in visual Studio:



Rental Service Interface
Next, I created an interface called IRentalService. This will define the service contract and its operations. code format="csharp" using System; using System.Collections.Generic; using System.ServiceModel;

namespace WCFSample {   [ServiceContract] interface IRentalService {       [OperationContract] string RentMovie(Movie movie); [OperationContract] string ReturnMovie(Movie myMovie); [OperationContract] List getCheckedOutMovies; } } code

Rental Service
Now I will implement the service contract: code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace WCFSample {   class RentalService : IRentalService {       List movies = new List;

public string RentMovie(Movie movie) {           movies.Add(movie); return String.Format("You have rented {0}", movie.Name);

}

public string ReturnMovie(Movie myMovie) {           String myMessage = String.Format("{0} is not checked out.", myMovie.Name);

foreach(Movie movie in movies){ if (movie.Name.ToUpper == myMovie.Name.ToUpper) {                   movies.Remove(movie); myMessage = String.Format("You have returned {0}", movie.Name); break; }           }

return myMessage; }

public List getCheckedOutMovies {           return movies; }

} } code

Movie Object
This object contains information about a particular movie. To keep it simple I have one property. code format="csharp" using System; using System.ServiceModel;

namespace WCFSample {   [Serializable] class Movie {       string _name;

public string Name {           get { return _name; } set { _name = value; } }   } } code

Application Config
Under the heading "Services" you must give in the name of the class that implements the interface. Then, tell it the address the service will run from. Finally, setup your endpoint to the Interface in which the service inherited. code format="xml"           <serviceBehaviors> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="False" /> </serviceBehaviors> </system.serviceModel> code

WCF Service Test Tool
After we write the code that will handle the interface properties, we can run the service. In visual studio, a test program will run to test out the newly created service. We can see that the 3 methods are visible and can be manipulated.



The first method is RentMovie. Here I will enter 3 movies that I want to rent. They are called: Star Wars, Willow, and Lord of the Rings. You can see the in the REQUEST box I add the name Star Wars to my movie name property and press invoke. I get a response that says that I have rented the movie Star Wars. I will do that for all three movies.



Now, I will see all the movies that are rented by calling the getCheckedOutMovies method. Here is the response:



You can see that I have 3 movies that have been checked out. Finally, I will return each one and here is the response:



If I check my movies collection now, I only have 2 left:



Good Things About my use of this pattern:
The proxy pattern is a powerful tool that can be used to control objects remotely. I have shown that WCF is .NET’s way of remotely controlling objects and is very powerful. I know many companies use WCF in distributed applications and it is important to understand how the proxy pattern works alongside the powerful tools used to control objects remotely. My Sample shows how easy it is to use WCF.

Not so good about my use of this pattern:
I know that in the real world I will be using a database and a better design for a movie rental system but I feel that I have shown that I understand the technology and can begin to use it to my advantage. This pattern is widely used and does not have a real disadvantage.

Click the file below to download the project files



=Template Pattern= The template pattern is a design pattern that is used to maximize the reuse of code by defining the steps of an algorithm in a class, then allowing the subclasses to provide the implementation for steps if they change between subclasses. The template pattern itself defines the skeleton of an algorithm. Each step is set as a method, which are then implemented by the subclasses. This allows the subclasses to define certain steps without changing the basic structure of the algorithm. In this structure, if there are methods that are common between all of the subclasses, they can be implemented in the superclass, rather than requiring all of the subclasses to implement the same method repeatedly.

Using the Template Pattern:
Here is a basic example of what this design pattern would look like.

code public abstract class TemplateExample {

void templateMethod { method1; method2; method3; method4; }

abstract void method1;

abstract void method2;

void method3 { //implement }

void method4 { //implement } } code In this class, the templateMethod calls all of the methods. No matter which subclass you are using, you can call this method to execute the algorithm it is defining. For this code, the first two methods change depending on which subclass you are using. Thus, the individual subclasses will have to implement these themselves. However, methods 3 and 4 are the same for all of the subclasses, so they are implemented here. This way, all of the inheriting methods inherit this implementation, allowing them all to use this code.

Hook Method
A hook method is a method that is declared in the abstract class, and given either an empty implementation, or a default implementation. This allows the subclasses to “hook into” the algorithm at various points, or to ignore the hooks. For the above code, we would therefore implement the two abstract methods in our superclass, like this: code public abstract class TemplateExample {

void templateMethod { method1; method2; method3; method4; }

void method1{ }

abstract void method2{ //default implementation }

void method3 { //implement }

void method4 { //implement } } code In this case, the subclasses do not have to implement any of the methods. For this code, the first method is given an empty implementation. Therefore, if it is not later overwritten by a subclass, it will not execute any code when called by the template method. In the second method, we have some default implementation. This code will be executed unless it is overwritten by the subclass.

Hollywood Principle
The Hollywood Principle is a way from preventing complication from caused by numerous dependencies. It allows the lower level components to be added to a system, but the high level components control when they are used, and how they are used. Our example from above is an example of this principle. Any clients of the subclasses of this class will only need to call this particular class. The subclasses will only be used when instantiating an object to provide an exact way to implement the unique stages of the process.

Good things about this Design Pattern
Using the template design pattern simplifies adding more subclasses later on, as well as updating the algorithm. To update the algorithm, you simply have to change the algorithm once in the parent class, and possible implement new methods in the children if they handle the new change differently. To add subclasses, the new classes only have to be able to implement the necessary methods in order to gain the same functionality of all of the other subclasses.

Not good things about this pattern
This pattern requires you create numerous classes that will all be very similar. This can cause some systems to contain a large number of nearly identical classes.

=Iterator Pattern= Frequently, a system uses inputs from numerous sources. Many times, the input from these sources can be used the same way, except that they are formatted differently. For a single data item, you can simply cast the item as another type, but usually data is given in large amounts stored in a data structure. In order to allow the system to use all of the input from multiple sources, regardless of the data structure it is contained you can use the iterator pattern. This pattern provides a method to access all of the elements within a data structure, regardless of what data structure is being used to store the elements. This way, you can use an input data structure no matter what structure it is.

Implementing an Iterator
An iterator is an interface and a series of implementations of that interface to serve as a uniform method for accessing data strcutres. The iterator interface will have three methods, the hasNext method and the next method, and a remove method. Below is the code for the iterator class in C#. code interface Iterator {	public bool hasNext;

public object next;

public void remove; } code You then will need to implement this interface with classes for each data structure that your system is being passed as input. So if your are being passed a list and a hash table, depending on the source, you would have an ListIterator class and a HashTableIterator class. Each of these classes will implement the Iterator interface, and will provide the code for each method. The hasNext method should check to ensure there are still data objects in the data structure. The next method will then return the next object in the data collection. Finally, the remove method will remove an object from a data structure. Below is an example of the implementation of this design pattern for an array. code class ArrayListIterator : Iterator {	List items; int position = 0;

public bool hasNext {		if (items[position+1].Equals(void)) return false; else return true; }

public object next {		position += 1; return items[position]; }

public void remove {		items.Remove(items[position]); } } code

Advantages of the Iterator Pattern
There are many advantages to using an iterator design pattern. It allows your system to be much more flexible with the input data types. If you are getting your input data from a third party, you do not need to force them to use a particular data structure. If you could only use one data structure, the third party may have to perform extensive reworking of their code in order to use the correct structure, or you may be required to extensively change your code to handle theirs. With the iterator pattern, you just have to implement the iterator, and then use the included methods to access the data within the data structure being represented by the iterator.

=Chapter 13 - Patterns in the Real World=

This chapter talks in detail what a design pattern is, the organization of the current patterns, and anti-patterns.

What is a pattern?
A pattern is defined as a solution to a problem in context. Here is a breakdown of this definition:
 * 1) Context – is a recurring situation in which the pattern applies.
 * 2) Problem – refers to the goal you are trying to achieve and to any constraints that occur in context.
 * 3) Solution – what you’re after, a general design that anyone can apply.

Becoming a Design Pattern Writer
It is possible to discover new design patterns but it is not easy to do. However there is a guideline on coming up with new design patterns:
 * Must be well versed in current design patterns because most new design patterns are variants on current ones.
 * Take time to reflect on the problems that have been encountered and the solutions to those problems.
 * Need to document the pattern in a way that others can read, understand, and apply them to their own problems.
 * Refine and refine your pattern more and more.
 * Pattern must apply to at least 3 real-world solutions to be a design pattern.

Design Pattern Template:

 * Name
 * Intent
 * Motivation
 * Applicability
 * Structure
 * Participants
 * Collaborations

Design Pattern Categories

 * Creational** – involve object instantiation and provide a way to decouple a client from the objects it needs to instantiate.
 * Singleton
 * Builder
 * Prototype
 * Abstract Factory
 * Factory Method


 * Behavioral** – makes sure objects interact and distribute properly
 * <span style="font-family: Arial,Helvetica,sans-serif;">Template
 * <span style="font-family: Arial,Helvetica,sans-serif;">Visitor
 * <span style="font-family: Arial,Helvetica,sans-serif;">Mediator
 * <span style="font-family: Arial,Helvetica,sans-serif;">Iterator
 * <span style="font-family: Arial,Helvetica,sans-serif;">Command
 * <span style="font-family: Arial,Helvetica,sans-serif;">Interpreter
 * <span style="font-family: Arial,Helvetica,sans-serif;">Memento
 * <span style="font-family: Arial,Helvetica,sans-serif;">Observer
 * <span style="font-family: Arial,Helvetica,sans-serif;">Chain of Responsibility
 * <span style="font-family: Arial,Helvetica,sans-serif;">State
 * <span style="font-family: Arial,Helvetica,sans-serif;">Strategy
 * Structural** – Compose classes or objects into larger structures
 * Decorator
 * Composite
 * Proxy
 * Façade
 * Flyweight
 * Bridge
 * Adapter

Anti-Pattern
These types of problems tell you how to go from a problem to a bad problem. Anti-patterns tell you:
 * Why a bad solution is attractive.
 * Why the solution in the long term is bad.
 * Other applicable patterns may provide a good solution.