Abner-Bilal-SSE658-Project3

toc

=SSE-658 Design Problems And Solutions=


 * Project group:** Abnerson Malivert & Bilal Ahmad
 * Project number:** 3
 * Design Patterns:** The Iterator Pattern, The Composite Pattern, The Template Method Pattern, The State Pattern

**Project References**
www.dofactory.com [|Head First design pattern]

**OVERVIEW**
This project covers the topic of using Object-Oriented design patterns. In project 1, we discussed the importance of using design patterns. SSE-658 project 3 also covers the importance of using design patterns to build applications that can easily be incorporated into other front end user applications. The design patterns covered in project 3 continues with the theme of building a good design pattern that makes it easy to either add new components or send data to new components in your application. According to the Summerville Software Engineering 8 book, reusable components play a big part in keeping cost down for corporation. Using design patterns will make your component easier to understand and integrate. This project covers chapter 8 to chapter 13 of the Head First Design Pattern book. The following paragraphs will cover the Iterator, Composite, Template, and State pattern.
 * Objective:**

**ITERATOR PATTERN**
To demonstrate the skills acquired from reading the Iterator Pattern chapter in the Head First Design Pattern book. The Car Inventory console application iterates through the current dealership inventories, and then displays the contents on the console. The Car Inventory console application uses the Iterator pattern. The Iterator pattern is used when you need your application to iterate through different collection items. With the Iterator pattern you can go through lists that have different sizes without having to write different loop statements to go through each list separately. The Iterator pattern also will let you iterate through a list, an array, a list array all at once, it does not care about the type the collection item is. The Car Inventory console application contains the following classes: The Car abstract Inventory class, the Nissan Dealership Inventory class, the Toyota Dealership Inventory class, the Iterator class, the Nissan Dealership Iterator class, the Toyota Dealership Iterator class, and the Cars class. Bellow is the Iterator Pattern schematic for the Car Inventory Console application.
 * Objective**:



Example 1: The Car Inventory Console application iterator pattern schematic above shows the different class implementation and where they stand as far as the iterator pattern. Below are important definitions: code format="csharp" abstract class CarAbstractInventory {        public abstract Iterator CreateIterator; }
 * Iterator Pattern:** Provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It’s a way to traverse and access elements.
 * Aggregate** (Car abstract inventory class)**:** Provides the interface for creating an iterator object. The car abstract inventory class contains the CreateIterator interface.

code
 * Concrete Aggregate (A)** (ToyotaDealershipInventory : CarAbstractInventory)**:** implements the create iterator interface using the CreateIterator method to return an iterator class instance of the ToyotaDealershipIterator. The addItems method is used to add cars into the Toyota cars list.

code format="csharp" class ToyotaDealershipInventory : CarAbstractInventory {

private List ToyotaCarsList = new List;

public override Iterator CreateIterator {           return new ToyotaDealershipIterator(ToyotaCarsList); }

public int Count {           get { return ToyotaCarsList.Count; } }

public void addItems(Cars car) {           ToyotaCarsList.Add(car); }   } code code format="csharp" class NissanDealershipInventory : CarAbstractInventory {       ArrayList  NissanCarsArray = new ArrayList;
 * Concrete Aggregate (B)** NissanDealershipInventory: CarAbstractInventory) : Implements the create iterator interface using the CreateIterator method to return an iterator class instance of the NissanDealershipIterator class. The addItems method is used to add cars into the Nissan cars list.

public override Iterator CreateIterator {           return new NissanDealershipIterator(NissanCarsArray); }

public int Count {           get { return NissanCarsArray.Count; } }

public void addItems(Cars car) {           NissanCarsArray.Add(car); }

} code code format="csharp" abstract class Iterator {       public abstract Cars First; public abstract Cars Next; public abstract bool IsDone; public abstract Cars CurrentItem;
 * Iterator** (Iterator Class)**:** interface for traversing or accessing elements.

} code · First – returns the first element of the Concrete aggregate class. · Next – returns the next element of the concrete aggregate class, this method is used to traverse through the concrete aggregate class. · IsDone – checks if we are at the last element of the concrete aggregate class, keeps you from getting a out of range exception. · CurrentItem – returns the current item. code format="csharp" class ToyotaDealershipIterator : Iterator {       private List ToyotaCarsList; private int position = 0; public ToyotaDealershipIterator(List ToyotaCarsList) {           this.ToyotaCarsList = ToyotaCarsList; }
 * Concrete Iterator (A)**( ToyotaDealershipIterator : Iterator): implements the iterator interface and also keeps track of the current position in the traversal of the aggregate.

public override Cars First {           return (Cars)ToyotaCarsList[0]; }

public override Cars Next {           Cars ret = null; if (position < ToyotaCarsList.Count - 1) {               ret = (Cars)ToyotaCarsList[++position]; }

return ret; }

public override bool IsDone {           return position >= ToyotaCarsList.Count; }

public override Cars CurrentItem {           return (Cars)ToyotaCarsList[position]; }   }

code code format="csharp" class NissanDealershipIterator : Iterator {       private ArrayList NissanCarsArray = new ArrayList; private int position = 0; public NissanDealershipIterator(ArrayList NissanCarsArray) {           this.NissanCarsArray = NissanCarsArray; }       public override Cars First {           return (Cars)NissanCarsArray[0]; }
 * Concrete Iterator (B)(** NissanDealershipIterator : Iterator) implements the iterator interface for the Nissan Dealership class and also keeps track of the current position in the traversal of the aggregate.

public override Cars Next {           Cars ret = null;

if (position < NissanCarsArray.Count - 1) {               ret = (Cars)NissanCarsArray[++position]; }

return ret; }

public override bool IsDone {           return (position >= NissanCarsArray.Count); }

public override Cars CurrentItem {           return (Cars)NissanCarsArray[position]; }   } code · Toyota dealership inventory is a List collection with three items in the collection. · Nissan dealership inventory is an ArrayList collection with two items in the collection. Figure 1 show a successful result when the program is executed. The program.cs makes instances of the Nissan and Toyota concrete aggregate class: code format="csharp" NissanDealershipInventory NissanCars = new NissanDealershipInventory; ToyotaDealershipInventory ToyotaCars = new ToyotaDealershipInventory; code Then the code creates new cars : code format="csharp" car = new Cars("Toyota","Corolla"," New red corolla with sports package ", 19999); car = new Cars("Nissan", "Maxima", " New gray Maxima with all the upgrades", 31999);
 * Test1**: Test one show the ability of the Iterator method to traverse through two different collections that are different types and size. For the first test:

code The .Add method is called to add the new cars to the appropriate Inventory: code format="csharp" ToyotaCars.addItems(car); NissanCars.addItems(car); code Then the program create instances of the Iterator class to create an Nissan and Toyota iterator: code format="csharp" Iterator NissanIterator = NissanCars.CreateIterator; Iterator ToyotaIterator = ToyotaCars.CreateIterator;

code Then the code assigns a variable to the first element of the collection list : code format="csharp" Cars Ncar = NissanIterator.First; Cars Tcar = ToyotaIterator.First; code A while loop is then use to traverse through the whole collection and then display the result on the console.

**Results of Iterator Pattern**
Figure 1 is the result when the program is executed.


 * Test2**: The same steps from test 1 occur except that the number of Nissan inventory items is increased to 4:

1. Add a new Concrete Aggregate class to the project called BmwDealershipInventory and make it implement the Car abstract Inventory class, which also means that it will have to implement to Equipment needed method from the Car abstract inventory class : code format="csharp" class BmwDealershipInventory : CarAbstractInventory code 2. Add a new concrete iterator class to the project called BmwDealershipIterator and make it implement the Iterator class, which also will need to implement the methods from the Iterator class: code format="csharp" class BmwDealershipIterator : Iterator code 3. In the program.cs class make an instance of the BmwDealershipInventory class : code format="csharp" BmwDealershipInventory BmwCars = new BmwDealershipInventory; code 4. Now follow step 3 to 10 from test 1. It took a total of 10 steps to add the BMW inventory, while no changes were made to other parts of the program, the program itself was changed by adding the new Aggregate and iterator class. The Iterator design pattern is good at traversing through different collection items, but is not beneficial if you need to add a lot of different pieces to the program. Figure 1-3 shows the result after adding the BMW inventory.
 * Test3**: The measurement of a good design is determined by the feasibility of adding a new section to the design. I am going to test the feasibility of adding a new Inventory list to the Equipment Manager Console application. The following steps shows what is needed to add a new concrete Aggregate called “BmwCarInventory”. Bmw car inventory will keep count of how many BMW cars are on the dealership lot.

**Composite Pattern**
The Cars inventory console application used the iterator design pattern. The iterator design pattern works great when it comes to traversing through collection items, but can be a headache if you are adding new components to the application. What if the dealership grew? And the owner wants to add new make and models to the inventory. The iterator pattern would not be the best choice to use, it would not only be tedious work, and it would also cause the application to be congested with classes. A better pattern to use for the Car Inventory application would be the composite pattern. The objective of this section is to introduce the composite pattern and also compare using the Composite pattern and the Iterator pattern for the Cars Inventory console application. Below is the Composite pattern schematic for the Cars Inventory console application.
 * Objective:**

Example 2: The Car Inventory console application Composite pattern schematic above shows the different class implementation and where they stand as far as the Composite pattern. Below are important definitions:

code format="csharp" abstract class CarsComponent {       public abstract int Count; public abstract void addItems(CarsComponent CarsComponent); public abstract string getBrand; public abstract string getModel; public abstract string getDescription; public abstract double getPrice; public abstract void PrintInventory; public abstract string InventoryName; } code
 * Composite Pattern:** Allows you to compose objects into tree structures to represent part-whole hierarchies. Composite pattern lets clients treat individual objects and compositions of objects uniformly.
 * Components** (CarsComponents)**:** This class declares the interface for the objects in the composition; it also declares the interface for the child components. It also implements the behavior for the interface common to all classes. The abstract method found in the CarsComponent are listed below.

o Count – returns the number of items in the inventory list. o addItems – adds items to the inventory list. o getBrand- returns the brand of the car. o getModel – returns the model of the car. o getDescription- returns the description of the car. o getPrice- returns the price of the car. o PrintInventory – prints inventory or inventory name to the console. o InventoryName – returns the name of the Inventory. code format="csharp" public override void addItems(CarsComponent CarsComponent) {           InventoryList.Add(CarsComponent); }       public override int Count {            return InventoryList.Count; }
 * Composite** (Inventory Class)**:** defines the behavior for components having children. A composite could be a Nissan car inventory, its children is a new Nissan maxima. The inventor class utilizes the methods below from the CarsComponent class.
 * Count – returns the number of items in the inventory list.
 * addItems – adds carcomponent items to the inventory list.
 * PrintInventory – prints inventory or inventory name to the console using an iterator to go through the inventory list.

public override void PrintInventory {           Console.WriteLine("\n" + InventoryName); Console.WriteLine; // don't forget to mention the IEnumerator in c#           IEnumerator iterator = InventoryList.GetEnumerator;

while (iterator.MoveNext) {               CarsComponent carComponents =  (CarsComponent)iterator.Current; carComponents.PrintInventory; code code format="csharp" public override string getModel {             return Model; }       public override string getBrand {           return Brand; }       public override double getPrice {           return price; }       public override string getDescription {          return Description; }       public override void addItems(CarsComponent CarsComponent) {           throw new NotImplementedException; }       public override int Count {           throw new NotImplementedException; }
 * Leaf** (Cars Class): represents the leaf objects of the composition and has no children. The Nissan Maxima from above is a leaf. The CarsClass utilizes the following methods from the CarsAbstract class:
 * getBrand- returns the brand of the car.
 * getModel – returns the model of the car.
 * getDescription- returns the description of the car.
 * getPrice- returns the price of the car.
 * PrintInventory – prints inventory name to the console

public override void PrintInventory {           Console.WriteLine("{0}   {1}  {2}           {3}", getBrand, getModel, getDescription, getPrice); Console.WriteLine("---"); } code code format="csharp" class Dealer {       CarsComponent allCarInventory; public Dealer(CarsComponent allCarInventory) {           this.allCarInventory = allCarInventory; }       public void print {           allCarInventory.PrintInventory; }   } code
 * Client** (Dealer Class): manipulates objects through the component interface. It calls out the PrintInventory method for the cars class to print the allinventory list.

The printInventory method from the Inventory class introduces a new concept in c#, which is the IEnumerator interface. The IEnumerator interface contains the methods to search through a collection, just like the iterator class and is found under systems.Collections. Enumerator are initially positioned one element before the first element. Below are the IEnumerator methods code format="csharp" IEnumerator iterator = InventoryList.GetEnumerator; code
 * getEnumerator – gets the enumerator for the collection.
 * Reset – resets the enumerator to the initial position.
 * Movenext – is a Boolean that returns false when you reach the end of the collection.
 * Current – returns the current data.

code format="csharp" CarsComponent NissanCars = new Inventory("Nissan Car Inventory "); CarsComponent ToyotaCars = new Inventory("Toyota Car Inventory "); code Then add items to both inventories: code format="csharp" ToyotaCars.addItems(new Cars("Toyota","Corolla"," New red corolla with sports package ", 19999)); NissanCars.addItems(new Cars("Nissan", "Sentra", " Used black Sentra with basic package", 10999));
 * Test1**: The figure 2 shows the result when the Car Inventory console application is executed. The list created are different sizes to check the composite patterns ability to iterate through different list using the IEnumerator Interface. First in the program.cs create an instance for the inventory that you wish to create:

code Instert all the inventories into one inventory: code format="csharp" CarsComponent AllInventory = new Inventory(" All THE CARS ON THE LOT !!!!"); AllInventory.addItems(ToyotaCars); AllInventory.addItems(NissanCars); code Create an instance of the Dealer class: code format="csharp" Dealer CarSalesMan = new Dealer(AllInventory); code Call the print method from the dealer class to print to the console : code format="csharp" CarSalesMan.print; code

**Results of Composite Pattern**
Figure 2 shows the result of the all inventory list.

code format="csharp" NissanCars.addItems(new Cars("Nissan", "GT-R", " New blue GT-R with a v8 turbo engine", 35999)); code Create a new inventory instance: code format="csharp" CarsComponent BMWCars = new Inventory(" BMW Car Inventory "); code Add items to the new inventory: code format="csharp" BMWCars.addItems(new Cars("BMW", "325I", "New charcoal 2010 bmw325i 5speed manual  ", 38999)); code Add BMW inventory to overall inventory: code format="csharp" AllInventory.addItems(BMWCars); code
 * Test2**: Test the capability of the composite pattern to add a new leaf to the Car Inventory console application. Figure 2-1 shows a new Nissan is added to the Nissan inventory. Use step 1 and Step 2 from test 1 to complete this test.
 * Test3**: Adding a new Inventory list with the composite pattern. The following steps are what it takes to add a new inventory to the Car Inventory console application using the composite pattern. Fig 1-3 displays the result with the new BMW inventory.

**Composite vs. Iterator Pattern**
The Composite pattern makes it easier to add the new BMW inventory to the Car inventory console application. Adding new components to the iterator class would congest everything and would require creating two new classes one for the concrete iterator and one for the inventory, while it only requires creating an instance of the inventory class for the composite iterator. The iterator pattern works well in iterating through a list, but does not work well with adding new components. The composite patterns works well with iterating through a list and adding new components to an application.

**TEMPLATE METHOD PATTERN**
To demonstrate the skills acquired by encapsulating pieces of algorithms so that subclasses can hook themselves at any time and therefore template method defines the steps of an algorithm and let subclasses implement the steps. The vehicle design console application uses the template method pattern and creates a template which assigns the responsibilities in designing the vehicle to its employees and instead of using duplicate method to test features or components of a different type of vehicle such as car or truck, it uses the same method name when testing features or components of a vehicle. When there’s code duplication, it is better to organize the design to make it easier to follow in the concrete classes which implement the operations required by the template method. Example 1: The vehicle design application utilizes the template method to ensure that the tasks are implemented by the subclasses and it utilizes a hook which gives subclasses a choice to utilize this method. The following figure 1-1 shows the block diagram of vehicle design application, its template method called Tasks and the concrete classes Car and truck.
 * Objective:**

Vehicle design is an abstract class which contains the template method called Tasks and two concrete classes called car and truck which implements the operations when the Tasks  method needs them. The methods in each concrete class Repair and Test  are given the same name to avoid duplication of the code and they each perform different task. The following two operations shown below are added to the abstract class which must be implemented by concrete subclasses. code format="csharp" //abstract for sub to use their own methods public abstract void Repair; public abstract void Test;

code A hook method **---** is declared in an abstract class called Vehicle Design and it is usually empty or has default implementation and it gives a choice to subclasses to call this method. The following code shows a hook method declared in a Vehicle Design class: code format="csharp" //Using Hook method To conform vehicle tests bool VehicleFeaturesTested {             return true; } code A condition is added to the template method called Tasks in which it asks the input user if the features or components of a vehicle are tested and if they are not tested, it then tells the user which feature or component is not functioning well and it also tell the user who is assigned to test or repair. code format="csharp" //superclass public abstract class VehicleDesign {           //Template public void Tasks {               AssignedToCarDesign; AssignedToEngine; AssignedToProgram; //condition if (VehicleFeaturesTested) {                   Repair; Test; }

} code Here the hook controls whether Vehicle Design checks part of the algorithm and to use a hook, the subclass overrides its method and a hook method here returns true as shown in VehicleFeaturesTested. The following two teams A and B are assigned to car and truck and the program.cs makes instances of it and assigns each team to its task. code format="csharp" static void Main {           VehicleDesign teamA = new Car; teamA.Tasks;

Console.WriteLine("\n"); VehicleDesign teamB = new Truck; teamB.Tasks;

Console.ReadKey; } code The following code ask the user if all the component and feature tests are performed before shipping the vehicle to a market. code format="csharp" private string getUserInput {               string answer = null;

try {                   answer = Console.ReadLine; }

catch {                   Console.Error.WriteLine("IO error trying to read your answer"); }

if (answer == "n") {                       return "no"; }                   else if (answer == "y") {                       return "y"; }                   else {                       return "no"; }               }

code The following is a concrete class which utilizes getUserInput method. code format="csharp" // ConcreteClassA public class Car : VehicleDesign {           public override void Repair

{               Console.WriteLine("Car components functioning well (y/n)?"); string answer = getUserInput;

if (answer.ToLower.StartsWith("y")) {

Console.WriteLine("All components of a car are functioning well"); }               else {                   Console.WriteLine("Patrick repair the brakes"); Console.WriteLine("Brakes need to be fixed"); }           } code The Test method in concrete class also utlizes the getUserInput method: code format="csharp" public override void Test {               Console.WriteLine("\nCar features working well (y/n)?"); string answer = getUserInput; if (answer.ToLower.StartsWith("y")) {                   Console.WriteLine("All features of a car are functioning well");

}               else {                   Console.WriteLine("Paul test the audio system"); Console.WriteLine("Audio system is not functioning well"); }

} code

**Results of Template Method Pattern**
The output of the program is shown below in figure 1-2: If the user answers no for the question in above figure1-2, then the application will show what component is not performing well and it will also show who is assigned to handle the task. Next the car features are being checked to ensure all the features of a car are in good in working condition before the vehicle is sent to the market. Here it can be observed that a hook method is utilized and the subclass override the method. Now the truck components and features are tested the same way and the subclass called Truck utilizes a hook method to override the following method. code format="csharp" //Using Hook method To conform vehicle tests bool VehicleFeaturesTested {             return true; }

code If the entire test for vehicle are verified and in good condition, then the vehicle can be shipped to the market.

**State Pattern**
The vehicle test takes advantage of the template method pattern and it works well when there’s a duplication of code, but to accomplish all the set of behaviors encapsulated in state objects, the state pattern design utilize a context class which contain number of internal states and it assist in delegating to other states. In the following example, vehicle gears application consist of context class called AutomaticGear, state interface and several concrete classes which handle requests from the AutomaticGear and each concrete class provides its own implementation. Example 2: The vehicle gears application takes advantage of the state pattern design to handle different behaviors for the automatic gear for instance, to shift a gear from parking to reverse, brake must be applied and only then the gear should be allowed to shift from parking to reverse which causes a different behavior; to make the code flexible and easier to maintain, the state pattern works well for applications that utilizes object to change the behavior when internal state changes and in this example it ensures gears are shifted properly without damaging the vehicle and before shipping the vehicle to the market. The following block diagram in figure 4-1 shows the state pattern diagram for vehicle gears application.
 * objective:**

As it can be seen that each state points to the state interface where methods cover the actions that are required by the automatic gear class; there are four tests that are required for automatic gear to function properly. Test 1: Shift vehicle gear from parking state to reverse. Test 2: Shift vehicle gear from reverse state to neutral. Test 3: Shift vehicle gear from neutral state to drive. Test 4: Shift vehicle gear from drive state to parking. Test 5: Checks whether gear shifted to parking state. The first test utilize the parking state and tell the user initially whether the gear is in parking state and then it checks all the states to make sure the gear is not in other states and then when change gear method is called, it should be able to shift to reverse state. The following code for change gear method under parking state moves the state to reverse state only when it is called. code format="csharp" public void changeGear {           Console.WriteLine("Brakes applied .... "); Console.WriteLine("Gear can shift to reverse gear now"); automaticGear.NumberOfTests; if (automaticGear.getCount == 2) {               automaticGear.setState(automaticGear.getReverseState); }

} code The program.cs utilizes the context class called Automatic Gear and sends one argument and in this case it starts the first test. code format="csharp" static void Main(string[] args) {

AutomaticGear gear = new AutomaticGear(1);

gear.Info; gear.parkingGear; gear.driveGear; gear.neutralGear; gear.reverseGear; gear.changeGear; Console.WriteLine("\n");

code

**Results of State Pattern**
The following is the output of the first test: When change gear method is called, it first updates the number of tests count from the context class as shown below: code format="csharp" automaticGear.NumberOfTests; code It checks the count and make sure the count is incremented. The reason for checking if coun is incremented is because the get count method is utilized to allow the following code to shift the state from parking state to reverse state. The following code under parking state shift the state to reverse state by using get reverse state method. code format="csharp" automaticGear.setState(automaticGear.getReverseState);

code The code under context class Automatic Gear include all get states: code format="csharp" // get States public State getParkingState {              return parkingState; }          public State getNeutralState {              return neutralState; }

public State getReverseState {              return reverseState; }

public State getDriveState {              return driveState; }

public int getCount {              return count; } code And in this case the get reverse state is called and now the gear is in reverse state; the following code confirms this and performs the second test which shifts the gear from reverse to neutral state. The program.cs checks each method for every action in state interface to make sure the gear is not in wrong state. The following code for State.cs is shown below which includes all the behaviors needed: code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace VehicleGears {   public interface State {        void parkingGear; void reverseGear; void changeGear; void neutralGear; void driveGear;

} } code

The gear is currently in neutral and all the methods are checked to make sure the gear is shifted properly when the change gear method is called. State interface **---** contains a method for every action in the automatic gear and then the state class is implemented for every state of the automatic gear. By utilizing the state, the behavior of each state is now in its own class and it simplify the codes by removing the entire if statements to handle all the states. Context class **---** is the class which contains number of internal states and in this case the automatic gear class is the context and it holds the states shown below: In Automatic gear class, all state objects are created and assigned in the constructor as shown below: code format="csharp" public class AutomaticGear {

State parkingState; State driveState; State neutralState; State reverseState; State _state;

int count = 1; // constructor for state instances public AutomaticGear(int testNumber) {               parkingState = new ParkingState(this); reverseState = new ReverseState(this); neutralState = new NeutralState(this); driveState = new DriveState(this); _state = new SetState(this); this.count = testNumber;

if (testNumber > 0) {                   _state = parkingState;

}           } code

The Code for the action methods which are delegated to the current state are included under Automatic Gear class as shown below: code format="csharp" public void parkingGear {

_state.parkingGear;

}

public void reverseGear {

_state.reverseGear; }

public void changeGear {

_state.changeGear;

}

public void neutralGear {

_state.neutralGear; }

public void driveGear {

_state.driveGear; }

code The following code in change gear method under reverse state: code format="csharp" public void changeGear {           Console.WriteLine("Brakes applied .... "); Console.WriteLine("Gear can shift to neutral gear now"); automaticGear.NumberOfTests; if (automaticGear.getCount == 3) {               automaticGear.setState(automaticGear.getNeutralState);

}       } code Continuing with our testing, the third test will first ensure that the gear is in proper state (neutral) and then when change method is called, it will shift the gear from neutral to drive state. And the fourth test: The final test in figure 2-5 verifies whether the gear is in proper state and to let the user know that the automatic gear of a vehicle is functioning well.

**Template Method Pattern vs. State pattern:**
Although both design patterns have their advantages when it comes to building application, but in the vehicle gears application, the state pattern has the advantage since it leave the vehicle gears application open to extension by adding new state classes and it is more flexible since it removes all the if statements in states and thus it simplify all the actions into a state class and each state class can jump from one state to another state easily. One of the disadvantages of using state pattern is that it increases the number of classes in the design process; in vehicle gears application, several states were added to ensure the gear shifting process work appropriately and each state contains the proper behavior for example, parking state checks the parking gear method to ensure whether the gear is in parking state; overall it makes it easier to maintain and more state classes can be added easily. The following figure 4-6 shows the automatic gears application diagram where it simplifies the process of shifting from one state to another. The template method let subclasses to decide how to implement steps as it was shown in vehicle design application and it avoid code duplication by assigning the same method name repair and test for each subclass. All the duplicated code is put into the super class vehicle design, but one of the disadvantage of using template method pattern is that it depends on the methods implemented in the super class whereas, the state pattern takes care of its behavior in its own state classes which makes it more flexible and easier to maintain by adding more state classes and knowing the behavior of each state through state diagram makes the code easier to follow.