SSE658+-+Project+3+for+Jill+Bufford+and+April+Penn

Project 3 - Design Patterns & Working with Wiki Pages SSE 658 Design Problems and Solutions  toc

By Jill Bufford & April Penn

For: Dr. Paul E. MacNeil



=Part I : Design Patterns =

Introduction
For this third and final project, Jill Bufford and April Penn have teamed up as partners. We will demonstrate five design patterns each as required and covered in Chapters 8 through 13 in our textbook, __Headfirst Design Patterns__. We have also used the Internet as a resource for this project.

Overview : What is a Design Pattern?
A design pattern is, simply, a solution to a recurring problem in software development. Design patterns outline communication and interaction between objects in common programming situations.

When talking about design patterns the book “[|Design Patterns: Elements of Reusable Object-Oriented Software]“, by the Gang of Four, is considered the authority on the subject. Their patterns are considered the foundation of all other patterns that have emerged. They divide patterns into three categories: Creational, Structural, and Behavioral.

The Template Method Design Pattern
We will discuss the Template as our first design pattern. This pattern looks for common functions and generalizes them by placing them in the base class. The Template Method defines the steps of an algorithm and allows subclasses to provide the implementation for one or more steps. This method gives us an important technique for code reuse.

Without this pattern, duplicated code may be required in many subclasses. It is very helpful in designing frameworks. This pattern defines the skeleton of a method/operation and allows subclasses to define some steps of it. Template methods allow subclasses to redefine a few of the steps of a method/algorithm without changing its structure/flow. The main theme behind this pattern is to give a chance to subclasses for redefining few operations/methods.

//Example Implementation//

 * To reduce replicated code in subclasses
 * To maintain the code properly for easy modifications

//Benefits Achieved Through The Template Method Pattern//

 * To improve code reusablility
 * Helpful in designing Frameworks

<span style="font-family: Verdana,Geneva,sans-serif;">Participants in this Pattern

 * <span style="font-family: Verdana,Geneva,sans-serif;">** Abstract Class: ** This class defines virtual and template methods. This template method will have calls to methods defined in concrete subclasses.
 * <span style="font-family: Verdana,Geneva,sans-serif;">** Concrete Class: ** <span style="font-family: Verdana,Geneva,sans-serif; font-size: 10pt;"> This class defines the methods inherited from base class along with definition to its internal members.

<span style="font-family: Verdana,Geneva,sans-serif;">Code Implementation
<span style="font-family: Verdana,Geneva,sans-serif;">This example explains about Template Method Display, which is having a skeleton calling a series of methods. Implementation of some of the methods is given to its subclasses.

First, create a new console application and name it as TemplatePatternSample. Now, add the code to program.cs as shown below:

Next, define Employee & Department classes [DTO] as shown below:

code format="csharp" class Employee {       public int EmpID { get; set; } public string EmpName { get; set; } public string Salary { get; set; } public Employee(int empID, string empName, string sal) {           this.EmpID = empID; this.EmpName = empName; this.Salary = sal; }   }    class Department {       public int DeptID { get; set; } public string DeptName { get; set; } public string Location { get; set; } public Department(int deptID, string deptName, string loc) {           this.DeptID = deptID; this.DeptName = deptName; this.Location = loc; }   }    #endregion code
 * 1) region DTO Defns

<span style="font-family: Verdana,Geneva,sans-serif;">Next, define the abstract class named as AbstractDAO:

code format="csharp" #region Abstract Class abstract class AbstractDAO {       public abstract void LoadDetails; public abstract void FormatAndDisplayDetails; public virtual void StartUp {           Console.WriteLine("Start of Processing"); Console.WriteLine("---"); }       public virtual void Dispose {           Console.WriteLine("End of Processing"); }       public void Display {           StartUp; LoadDetails; FormatAndDisplayDetails; Dispose; }   }    #endregion code

<span style="font-family: Verdana,Geneva,sans-serif;">Here, we defined Display method with a series of method calls. LoadDetails and FormatAndDisplayDetails are declared as abstract making it to redefine in its subclasses.

We will define two concrete subclasses for AbstractDAO as shown below: code format="csharp" #region Concrete Classes class Employees: AbstractDAO {       private List<Employee> empList = new List<Employee>; public override void LoadDetails {           //Get Data From Database. empList.Add (new Employee (10,"TEST","2000")); empList.Add (new Employee (20,"TEST1","3000")); empList.Add (new Employee(30, "TEST2", "4000")); }       public override void FormatAndDisplayDetails {          //Add $ to Salary foreach (Employee emp in empList) {               emp.Salary = "$" + emp.Salary; //Display all Employees Details. Console.WriteLine("Employee ID: " + emp.EmpID); Console.WriteLine("Employee Name: " + emp.EmpName); Console.WriteLine("Employee Salary: " + emp.Salary); Console.WriteLine("---"); }       }    }    class Departments : AbstractDAO {       private List<Department> deptList = new List<Department>; public override void LoadDetails {           //Get Data From Database. deptList.Add(new Department(1000, "HRA", "BLORE")); deptList.Add(new Department(2000, "FIN", "HYD")); deptList.Add(new Department(3000, "MARKETING", "DEL")); }      public override void FormatAndDisplayDetails {           //Expand Location. foreach (Department dept in deptList) {               if (dept.Location == "BLORE") {                   dept.Location = "BANGALORE"; }               else if (dept.Location == "HYD") {                   dept.Location = "HYDERABAD"; }               else {                   dept.Location = "DELHI"; }               //Display all Departments Details. Console.WriteLine ("Department ID: " + dept.DeptID); Console.WriteLine("Department Name: " + dept.DeptName); Console.WriteLine("Department Location: " + dept.Location); Console.WriteLine("---"); }       }    }    #endregion code

<span style="font-family: Verdana,Geneva,sans-serif;">In LoadDetails, load Employees and Departments details. Later, we format and display those details in FormatAndDisplayDetails. We will test it out by calling those methods in Main method as shown below:

code format="csharp" static void Main(string[] args) {           //Call Employees. AbstractDAO employees = new Employees; employees.Display; //Call Departments. AbstractDAO departments = new Departments; departments.Display; Console.ReadLine; } code

**<span style="font-family: Verdana,Geneva,sans-serif;">Sample output from the program: **
<span style="font-family: Verdana,Geneva,sans-serif;">Based on Instance type, AbstractDAO class will call corresponding methods of Employee or Department class. Here, I am displaying employee's details followed by department's details. Now, run the application and the output will be as shown below:



<span style="font-family: Verdana,Geneva,sans-serif;">The Strategy Design Pattern
<span style="font-family: Verdana,Geneva,sans-serif;">The Strategy and State Design Patterns are “twins that were separated at birth”, according to our textbook. The GOF Strategy and State patterns are remarkably similar and it is really only a minor implementation detail that distinguishes the two.

//<span style="font-family: Verdana,Geneva,sans-serif;">Example Implementation //
<span style="font-family: Verdana,Geneva,sans-serif;">The way I like to think of the strategy pattern is (1) encapsulation of a method into a class and (2) being able to swap out this method with different implementations.

We'll often come across a situation when building code where we have long "if-then-else" chains in our class methods which determine how the method will behave. This is a perfect situation to refactor to a Strategy pattern, especially if we have cut-n-pasted the "if-then-else" chain to other methods. These chains can be replaced by a single strategy.

<span style="font-family: Verdana,Geneva,sans-serif;">Code Implementation
<span style="font-family: Verdana,Geneva,sans-serif;">So, basically all we are doing is creating a class with "pluggable" functionality. For instance, if we have the following interface that defines a "Calculate" strategy: code format="csharp" interface ICalculator {   int Calculate(int inputA, int inputB); } code

<span style="font-family: Verdana,Geneva,sans-serif;">And two implementations of the strategy:

code format="csharp" class Adder : ICalculator {   #region ICalculator Members

public int Calculate(int inputA, int inputB) {       return inputA + inputB; }

#endregion }

class Subtractor : ICalculator {   #region ICalculator Members

public int Calculate(int inputA, int inputB) {       return inputA - inputB; }

#endregion } code

<span style="font-family: Verdana,Geneva,sans-serif;">We can create a class where we can "plug-in" either strategy to be used for execution of the "Calculate" method below:

code format="csharp" class NumberChanger {   public NumberChanger(ICalculator calculationStrategy) {       m_calculationStrategy = calculationStrategy; m_state = 1; }

private ICalculator m_calculationStrategy; private int m_state;

public int State {       get { return m_state; } }

internal ICalculator CalculationStrategy {       get { return m_calculationStrategy; } set { m_calculationStrategy = value; } }

public int Calculate(int input) {       m_state = m_calculationStrategy.Calculate(m_state, input); return m_state; } } code

<span style="font-family: Verdana,Geneva,sans-serif;">This is how we would use the class:

code format="csharp" StrategyPattern.NumberChanger strategyCalculator = new StrategyPattern.NumberChanger(new Adder);

while (strategyCalculator.State < 10) {   Console.WriteLine("StrategyPattern.NumberChanger.State = " + strategyCalculator.State); strategyCalculator.Calculate(1); }

strategyCalculator.CalculationStrategy = new Subtractor;

while (strategyCalculator.State > 0) {   Console.WriteLine("StrategyPattern.NumberChanger.State = " + strategyCalculator.State); strategyCalculator.Calculate(1); } code

**<span style="font-family: Verdana,Geneva,sans-serif;">Sample output from the program: **
<span style="font-family: Verdana,Geneva,sans-serif;"> StrategyPattern.NumberChanger.State = 1 StrategyPattern.NumberChanger.State = 2 StrategyPattern.NumberChanger.State = 3 StrategyPattern.NumberChanger.State = 4 StrategyPattern.NumberChanger.State = 5 StrategyPattern.NumberChanger.State = 6 StrategyPattern.NumberChanger.State = 7 StrategyPattern.NumberChanger.State = 8 StrategyPattern.NumberChanger.State = 9 StrategyPattern.NumberChanger.State = 10 StrategyPattern.NumberChanger.State = 9 StrategyPattern.NumberChanger.State = 8 StrategyPattern.NumberChanger.State = 7 StrategyPattern.NumberChanger.State = 6 StrategyPattern.NumberChanger.State = 5 StrategyPattern.NumberChanger.State = 4 StrategyPattern.NumberChanger.State = 3 StrategyPattern.NumberChanger.State = 2 StrategyPattern.NumberChanger.State = 1

<span style="font-family: Verdana,Geneva,sans-serif;">The State Design Pattern
<span style="font-family: Verdana,Geneva,sans-serif;">The State Pattern is simply a Strategy Pattern where the class manages its own strategy based on its state (thus the name).

<span style="font-family: Verdana,Geneva,sans-serif;">//Example Implementation//
<span style="font-family: Verdana,Geneva,sans-serif;">If we have the same ICalculator, Adder, and Subtractor classes from above, we could use them in an implementation of the State pattern as follows (Note how the class sets its own strategy based on its state in the Calculate method):

code format="csharp" class NumberChanger {   public NumberChanger {       m_calculationStrategy = m_adder; m_state = 1; }

private ICalculator m_calculationStrategy; private int m_state; private static ICalculator m_adder = new Adder; private static ICalculator m_subtractor = new Subtractor;

public int State {       get { return m_state; } }

internal ICalculator CalculationStrategy {       get { return m_calculationStrategy; } set { m_calculationStrategy = value; } }

public int Calculate(int input) {       m_state = m_calculationStrategy.Calculate(m_state, input);

// this is where the interal state is evaluated and // the strategy is set if (m_state >= 10) {           m_calculationStrategy = m_subtractor; }       else if (m_state < 1) {           m_calculationStrategy = m_adder; }       return m_state; } } code

<span style="font-family: Verdana,Geneva,sans-serif;">Code Implementation
code format="csharp" StatePattern.NumberChanger stateCalculator = new StatePattern.NumberChanger;

while (stateCalculator.State > 0) {   Console.WriteLine("StatePattern.NumberChanger.State = " + stateCalculator.State); stateCalculator.Calculate(1); } code

<span style="font-family: Verdana,Geneva,sans-serif;">Sample Output from this program:
<span style="font-family: Verdana,Geneva,sans-serif;">StatePattern.NumberChanger.State = 1 StatePattern.NumberChanger.State = 2 StatePattern.NumberChanger.State = 3 StatePattern.NumberChanger.State = 4 StatePattern.NumberChanger.State = 5 StatePattern.NumberChanger.State = 6 StatePattern.NumberChanger.State = 7 StatePattern.NumberChanger.State = 8 StatePattern.NumberChanger.State = 9 StatePattern.NumberChanger.State = 10 StatePattern.NumberChanger.State = 9 StatePattern.NumberChanger.State = 8 StatePattern.NumberChanger.State = 7 StatePattern.NumberChanger.State = 6 StatePattern.NumberChanger.State = 5 StatePattern.NumberChanger.State = 4 StatePattern.NumberChanger.State = 3 StatePattern.NumberChanger.State = 2 StatePattern.NumberChanger.State = 1

<span style="font-family: Verdana,Geneva,sans-serif;">The Iterator Design Pattern
<span style="font-family: Verdana,Geneva,sans-serif;">The Iterator pattern provides a way to create classes that can be used with foreach statements without implementing the IEnumerator & IEnumerable interfaces. When the compiler detects iterator it will automatically generate the current, MoveNext and dispose method of IEnumerable or IEnumerator interfaces. This is typically explained with employees and department classes GetEnumerator method, typically by implementing IEnumerable or IEnumerable <ItemType>. You tell the compiler what to yield using the C# yield return statement.

In object-oriented programming, the Iterator pattern is a design pattern in which iterators are used to aggregate an object sequentially without exposing its underlying representation. An Iterator object encapsulates the internal structure of how the iteration occurs.

//<span style="font-family: Verdana,Geneva,sans-serif;">Example Implementation //
<span style="font-family: Verdana,Geneva,sans-serif;">This example explains how to use the Iterator pattern to manipulate any collection of objects. To explain this we use two interfaces IEnumerator and IEnumerables.

<span style="font-family: Verdana,Geneva,sans-serif;">Code Implementation
<span style="font-family: Verdana,Geneva,sans-serif;">We have a class called Employee, which stores his ID and name.

code format="vbnet" Public Class Employee Private m_nID As Integer Private m_strName As String

Public Sub New(ByVal nID As Integer, ByVal strName As String) m_nID = nID m_strName = strName End Sub

Public ReadOnly Property EmployeeID As Integer Get Return Me.m_nID End Get End Property

Public ReadOnly Property EmployeeName As String Get Return Me.m_strName End Get End Property End Class code

<span style="font-family: Verdana,Geneva,sans-serif;">We have two more classes

<span style="font-family: Verdana,Geneva,sans-serif;"> code format="vbnet" Public Class EnumerateEmployee Implements IEnumerator Private m_nPosition As Integer Private m_ArrEmployee As ArrayList = New ArrayList
 * 1) <span style="font-family: Verdana,Geneva,sans-serif;">**EmployeeList**, which is derived from the interface IEnumerable. So this class should implement //**GetEnumerator**// function. This function returns an object of EnumerateEmployee which is derived from IEnumerator.
 * 2) <span style="font-family: Verdana,Geneva,sans-serif;">**EnumerateEmployee**, which is derived from the interface IEnumerator. So this class should implement two functions namely //**MoveNext**// and //**Reset**// and a property called //**Current**//. In this class I created four objects of Employee objects and added to an array list. MoveNext function will iterate through this collection.

Public Sub New m_nPosition = -1 m_ArrEmployee.Add(New Employee(1, "Kamsa")) m_ArrEmployee.Add(New Employee(2, "Rama")) m_ArrEmployee.Add(New Employee(3, "Sita")) m_ArrEmployee.Add(New Employee(4, "Gopala")) End Sub

Public Function MoveNext As Boolean Dim b_return As Boolean = False System.Threading.Interlocked.Increment(m_nPosition) If m_nPosition < m_ArrEmployee.Count Then b_return = True End If       Return b_return End Function

Public ReadOnly Property Current As Object Get Return m_ArrEmployee(m_nPosition) End Get End Property

Public Sub Reset m_nPosition = -1 End Sub End Class code

<span style="font-family: Verdana,Geneva,sans-serif;">In order to execute this class, create a window application and put the following code in the button click event.

code format="vbnet" Dim strName As String Dim nID As Integer Dim objEmpList As EmployeeList = New EmployeeList Dim objEnumEmp As IEnumerator = objEmpList.GetEnumerator While objEnumEmp.MoveNext Dim objEmployee As Employee = CType(objEnumEmp.Current, Employee) nID = objEmployee.EmployeeID strName = objEmployee.EmployeeName End While code

<span style="font-family: Verdana,Geneva,sans-serif;">The Composite Design Pattern
<span style="font-family: Verdana,Geneva,sans-serif;">The composite pattern allows a developer to create tree structures out of objects. This is easily seen in the form of a hierarchy. The hierarchy could be in any place but we usually find it in the corporate world with the lovely notion of bosses.

//<span style="font-family: Verdana,Geneva,sans-serif;">Example Implementation //
<span style="font-family: Verdana,Geneva,sans-serif;">Our example here we will call “TheCompany”, this could be any company you want to make it. It could be AT&T or Microsoft. So, here at "TheCompany" we have 4 departments: Marketing, Human Resources, Engineering and Consulting and with each department there is a manager. Our Marketing manager is Bob, our Human Resources manager is Sue, our Engineering manager is Ellen and our Consulting manager is Tim. Each of these managers reports directly to "TheCompany" and as you can see in the tree structure created below each manager has 2 people that report to them and that group of people has 3 people each that report to them.



<span style="font-family: Verdana,Geneva,sans-serif;">With the composite each person would be an object or a component and the component would have children according to where it falls in the hierarchy. And we could create for each object or component a set of attributes that would distinguish where in the structure the object/component or worker would fall. So for Ellen’s attributes would be:
 * <span style="font-family: Verdana,Geneva,sans-serif;">dept: Engineering
 * <span style="font-family: Verdana,Geneva,sans-serif;">title: manager
 * <span style="font-family: Verdana,Geneva,sans-serif;">teamLead: TheCompany

<span style="font-family: Verdana,Geneva,sans-serif;">Tony’s attributes that would put him in his spot on the hierarchy would be:
 * <span style="font-family: Verdana,Geneva,sans-serif;">dept: consulting
 * <span style="font-family: Verdana,Geneva,sans-serif;">title: worker bee
 * <span style="font-family: Verdana,Geneva,sans-serif;">teamLead: Alice

<span style="font-family: Verdana,Geneva,sans-serif;">So, now that we have established attributes for the object/component (workers) we can see what a composite pattern would do. We could apply applications to the hierarchy as a whole and we could pick out groups of people depending on which group was needed.

If there was a staff meeting and according to the staff meeting rule we would need all managers to be at this meeting the system could select all managers by their attribute and send a meeting request through the email system and this would select: Bob, Sue, Ellen and Tim. If there were some training that all worker bees would need then the same type of selection would be made on the “title” attribute for the objects and all the worker bees would be selected for this training event.

<span style="font-family: Verdana,Geneva,sans-serif;">Summary: Design Patterns
<span style="font-family: Verdana,Geneva,sans-serif;">As Tim Gluvna pointed out in one of his Listserv messages, often you will find you have used a number of design patterns, not knowing that they were some documented standard for approaching a situation. In this project, we’ve discussed and illustrated five of the common design patterns used in the industry. It’s helpful to know formally, what they really are and why and when they are used, so you can apply them on purpose and not accidentally.

<span style="font-family: Verdana,Geneva,sans-serif;">Conclusion
<span style="font-family: Verdana,Geneva,sans-serif;">We hope this article gives you a better idea of different design patterns and their uses. We explained and gave examples for the Template Method, the Strategy, the State, The Iterator and the Composite Design Patterns. Our explanations of the State and Strategy patterns show all how closely they are related. Both these patterns are really a Strategy pattern at the core where the only difference is that the State pattern maintains its own Strategy. All of these design patterns are very useful and have their own specialty for implementation. Use design patterns where they are needed and use them wisely.

=<span style="font-family: Verdana,Geneva,sans-serif;">Part II : Working with Wiki Pages =

<span style="font-family: Verdana,Geneva,sans-serif;">Part II of this project involves working with Wiki pages. Wiki pages are an easy way to build a web site that makes it easy to collaborate with other individuals and groups. Part II demonstrates our learning about how to create and edit Wiki pages, add special formatting to them, and how to create links. Jill’s Wiki name is JILL-BUFFORD and April’s Wiki name is aprilpenn.

As Jill learned to use Wiki, she took screen shots along the way. I found the tutorials to be extremely helpful as well as short and concise. The nice thing about Wiki is that you can select the degree of openness with others, as well as having the option of a wide range of types of Wiki pages, from simple to complex.

Now for the flow Jill used to learn Wiki…

<span style="font-family: Verdana,Geneva,sans-serif;">**Step One: My first attempt to create the main page.**



<span style="font-family: Verdana,Geneva,sans-serif;">


 * Step Two: My first attempt to edit the main page.**



<span style="font-family: Verdana,Geneva,sans-serif;">**Step Three: More familiar with editing, I started adding pieces of my first project to my Wiki.**



<span style="font-family: Verdana,Geneva,sans-serif;">**Step Four: Adding another section of my first project to my Wiki.**



<span style="font-family: Verdana,Geneva,sans-serif;">**Step Five: Personalizing my Wiki by adding special formatting and themes.**



<span style="font-family: Verdana,Geneva,sans-serif;">**Step Six: Added page two of the Wiki with special formatting and my theme.**



<span style="font-family: Verdana,Geneva,sans-serif;">**Step Seven: While I was doing this, I was also going through other tutorials and in this screenshot, I added external links.**



<span style="font-family: Verdana,Geneva,sans-serif;">**Step Eight: Last, I’m adding another project page to my Wiki, entitled Overview.**



<span style="font-family: Verdana,Geneva,sans-serif;">Here are some tips from April to configure your Wiki page with your style…

April’s Home Page: There are some slight modifications that she did to get her page to look like this in the following steps you will see how.



<span style="font-family: Verdana,Geneva,sans-serif;">**Select Manage Wiki on your wikispace menu.**



<span style="font-family: Verdana,Geneva,sans-serif;">When you choose to manage your wiki there will be many options on the next menu page. Choose “Look and Feel.” On the “Look and Feel” page choose “Themes and Colors.”

<span style="font-family: Verdana,Geneva,sans-serif;">Once on the “Themes and Colors” page, there are 13 different themes offered by Wikispaces and then you can customize each of those themes to your own liking.

<span style="font-family: Verdana,Geneva,sans-serif;">Looking at the color wheel below you can see that the background color April chose is a blue green color coded as#6bb3b0, which is on the left border and the top border. The menu color that April chose is a light yellow coded #f5f99f and is surrounding the Wiki menu for April’s Pages: Home, Journal, Project 1, 2 and 3. The Text is Black (#000000) and the links are a bright blue (#0000ff). Any color in the color wheel could be chosen for each of the 4 categories in your wiki.



<span style="font-family: Verdana,Geneva,sans-serif;">One of the biggest lessons to learn, when dealing with an editor that chooses for the developer how the text, code and photos will be displayed, it can prove to be a problem. The wiki would not always show what I was asking it to do. A fellow classmate pointed me to the wikitext editor where I could modify the font choices manually and once I learned the syntax for this site the formatting was a breeze.

I found that if I wanted a line to be considered "Header" the line was surrounded by the '='. For "Header 1" the line had one '=' on the beginning of the line and one on the end. For "Header 2" the line had two '=' on the beginning of the line and two on the end. The font became easier, the modifications to the pages became twice as fast and all I had to do was continue the same font throughout the page and double check the page with a "save" every so often. I find that text editors cut the work in half. I was very thankful for the tip and the time saving! I hope this can help other's too.