Anda di halaman 1dari 16

Design Patterns

Version 1.0
Week - 9

The information in this document is confidential to the person/entity to whom it is addressed and
should not be disclosed to any other person/entity. It may not be reproduced in whole, or in part,
nor may any of the information contained therein be disclosed without the prior consent of the
management of ISGN (the Company). Any form of reproduction, dissemination, copying,
disclosure, modification, distribution and or publication of this material is strictly prohibited. ISGN
Confidential and Proprietary. 2014 ISGN Corporation.

ISGN - Confidential

ISGN - Confidential
www.isgn.com | p.1

Document Information
Line of Business / Department

Technology

Design Patterns
Internal Only
Design Patterns V1.0
Training Presentation
1.0
Detail
Geetha V
Sinila Mundengara
Geetha V
NA
20th March 2015
20th March 2015

Subject
Distribution
Procedure Name
Document Type
Version
Level
Document Author / Owner
Reviewed By
Approved (Internal) By
Approved (External) By
Approval Date
Effective Date

Change History
Sl No Version #
1

1.0

Change Description
New document

Section Number

Changed By

Release Date
20th March 2015

The information in this document is confidential to the entity to which it is addressed and should not be disclosed to any other person. It
may not be reproduced in whole, or in part, nor may any of the information contained therein be disclosed without the prior consent of
the management of ISGN (the Company). A recipient may not solicit, directly or indirectly (whether through an agent or otherwise) the
participation of another institution or person without the prior approval of the management of the Company. Any form of reproduction,
ISGN - Confidential
dissemination, copying, disclosure, modification, distribution, and or publication of this material is strictly prohibited.
www.isgn.com | p.2

Week - 9

ISGN - Confidential
www.isgn.com | p.3

Learning Objectives
At the end of the session, the learners will have a good
understanding about:
Strategy Pattern
Template Method Pattern
Visitor Pattern

ISGN - Confidential
www.isgn.com | p.4

Strategy Pattern
In a scenario where we need to define a family of algorithms,
encapsulate each one, and make them interchangeable, Strategy
lets the algorithm vary independently from clients that use it.
Family of Algorithms- The definition says that the pattern
defines the family of algorithms; it means we have
functionality (in these algorithms) which will do the same
common thing for our object, but in different ways
Encapsulate each one of them- The pattern would force you
to place your algorithms in different classes (encapsulate
them). Doing so would help us in selecting the appropriate
algorithm for our objects
Make them interchangeable- The beauty with strategy pattern
is, we can select at run time which algorithm we should apply
to our object and can replace them with one another
ISGN - Confidential
www.isgn.com | p.5

Strategy Pattern UML Diagram

Fig 1.0

ISGN - Confidential
www.isgn.com | p.6

Strategy Pattern - Example


Lets go through an example which would use the strategy
pattern and would make everything clear. Suppose you have
to write an application which could sort different types of
objects, that means it can sort the scholar numbers of
students in the university, the ticket numbers of railway
passengers or even more the names of all people residing in
a country.

ISGN - Confidential
www.isgn.com | p.7

Strategy Pattern - Example


Suppose we have formulated (be it correct or wrong)

that quick sort would be good for sorting names of country


residents, the merge sort would be suitable for scholar
numbers (ints/doubles) and heap sort would be best for
sorting the railway passengers. This is the optimum
scenario where we can apply the strategy pattern.
We will be encapsulating all our algorithms and select the
one we would be using at runtime

ISGN - Confidential
www.isgn.com | p.8

Strategy Pattern - Code


public enum ObjectToSort
{
StudentNumber,
RailwayPassengers,
CountyResidents
}
public interface ISortingStrategy
{
void Sort<T>(List<T> dataToBeSorted);
}
public class QuickSort : ISortingStrategy
{
public void Sort<T>(List<T>
dataToBeSorted)
{
//Logic for quick sort
}
}
public class MergeSort : ISortingStrategy
{
public void Sort<T>(List<T>
dataToBeSorted)
{
//Logic for Merge sort
}

public class HeapSort : ISortingStrategy

{
public void Sort<T>(List<T>
dataToBeSorted)
{
//Logic for Heap sort
}
}
class Program
{
static void Main(string[] args)
{
ISortingStrategy sortingStrategy = null;
//Sorting the countyResidents
List<string> countyResidents = new
List<string>{ "ad","ac", "ax", "zw" };
sortingStrategy =
GetSortingOption(ObjectToSort.CountyRes
idents);
sortingStrategy.Sort(countyResidents);
//Sorting student numbers
List<int> studentNumbers = new
List<int>{ 123,678,543, 189};
sortingStrategy =
GetSortingOption(ObjectToSort.StudentN
umber);
sortingStrategy.Sort(studentNumbers);

//Sorting railway passengers


List<string> railwayPassengers = new

List<string> { "A21", "Z2", "F3", "G43" };


sortingStrategy =
GetSortingOption(ObjectToSort.RailwayPa
ssengers);

sortingStrategy.Sort(railwayPassengers);
}
private static ISortingStrategy
GetSortingOption(ObjectToSort
objectToSort)
{
ISortingStrategy sortingStrategy = null;
switch (objectToSort)
{
case ObjectToSort.StudentNumber:
sortingStrategy = new
MergeSort();
break;
case
ObjectToSort.RailwayPassengers:
sortingStrategy = new HeapSort();
break;
case ObjectToSort.CountyResidents:
sortingStrategy = new QuickSort();
break;
default:
break;
}
return sortingStrategy;
}
}
}

ISGN - Confidential
www.isgn.com | p.9

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

ISGN - Confidential
www.isgn.com | p.10

Template Pattern UML diagram

Fig 2.0

ISGN - Confidential
www.isgn.com | p.11

Template Pattern

Template method is a handy pattern to run common


functionality of a base class from the child class. The skeleton
of this pattern will be an abstract base class
with abstract methods and a common method with
implementation which will be used by the implementer
classes of the abstract class. So all objects of the child type
can use the common method functionality.

ISGN - Confidential
www.isgn.com | p.12

Template Pattern
using System;
using System.Data;
using System.Data.OleDb;
namespace
DoFactory.GangOfFour.Template.RealWorld
{
/// <summary>
/// MainApp startup class for Real-World
/// Template Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
DataAccessObject daoCategories = new
Categories();
daoCategories.Run();
DataAccessObject daoProducts = new Products();
daoProducts.Run();
// Wait for user
Console.ReadKey();
}
}
/// <summary>
/// The 'AbstractClass' abstract class
/// </summary>
abstract class DataAccessObject
{
protected string connectionString;
protected DataSet dataSet;

public virtual void Connect()


{
// Make sure mdb is available to app
connectionString =
"provider=Microsoft.JET.OLEDB.4.0; " +
"data source=..\\..\\..\\db1.mdb";
}
public abstract void Select();

public abstract void Process();


public virtual void Disconnect()
{
connectionString = "";
}
// The 'Template Method'
public void Run()
{
Connect();
Select();
Process();
Disconnect();
}
}
/// <summary>
/// A 'ConcreteClass' class
/// </summary>
class Categories : DataAccessObject
{
public override void Select()
{
string sql = "select CategoryName from
Categories";
OleDbDataAdapter dataAdapter = new
OleDbDataAdapter(
sql, connectionString);

/// <summary>
/// A 'ConcreteClass' class
/// </summary>
class Products : DataAccessObject
{
public override void Select()
{
string sql = "select ProductName from Products";
OleDbDataAdapter dataAdapter = new
OleDbDataAdapter(
sql, connectionString);
dataSet = new DataSet();
dataAdapter.Fill(dataSet, "Products");
}

public override void Process()


{
Console.WriteLine("Products ---- ");
DataTable dataTable =
dataSet.Tables["Products"];
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["ProductName"]);
}
Console.WriteLine();
}
}
}

dataSet = new DataSet();


dataAdapter.Fill(dataSet, "Categories");
}
public override void Process()
{
Console.WriteLine("Categories ---- ");

DataTable dataTable =
dataSet.Tables["Categories"];
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["CategoryName"]);
}
Console.WriteLine();
}
}

ISGN - Confidential
www.isgn.com | p.13

Visitor Pattern
Represent an operation to be performed on the elements of
an object structure. Visitor lets you define a new operation
without changing the classes of the elements on which it
operates.

ISGN - Confidential
www.isgn.com | p.14

Visitor Pattern
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Setup employee collection
Employees e = new Employees();
e.Attach(new Clerk());
e.Attach(new Director());
e.Attach(new President());
// Employees are 'visited'
e.Accept(new IncomeVisitor());
e.Accept(new VacationVisitor());

}
}

public void Attach(Employee employee)


{
_employees.Add(employee);
}

/// <summary>
/// The 'Element' abstract class
/// </summary>
abstract class Element
{
public abstract void Accept(IVisitor visitor);
}

public void Detach(Employee employee)


{
_employees.Remove(employee);
}

/// <summary>
/// The 'ConcreteElement' class
/// </summary>
class Employee : Element
{
private string _name;
private double _income;
private int _vacationDays;

// Wait for user


Console.ReadKey();

public void Accept(IVisitor visitor)


{
foreach (Employee e in _employees)
{
e.Accept(visitor);
}
Console.WriteLine();
}
}

// Constructor
public Employee(string name, double income,
int vacationDays)
{
this._name = name;
this._income = income;
this._vacationDays = vacationDays;
}

}
}
/// <summary>
/// The 'Visitor' interface
/// </summary>
interface IVisitor
{
void Visit(Element element);
}

// Three employee types


class Clerk : Employee
{
// Constructor
public Clerk()
: base("Hank", 25000.0, 14)
{
}
}

// Gets or sets the name


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

/// <summary>
/// A 'ConcreteVisitor' class
/// </summary>
class IncomeVisitor : IVisitor
{
public void Visit(Element element)
{
Employee employee = element as Employee;

class Director : Employee


{
// Constructor
public Director()
: base("Elly", 35000.0, 16)
{
}
}

// Gets or sets income


public double Income
{
get { return _income; }
set { _income = value; }
}

// Provide 10% pay raise


employee.Income *= 1.10;
Console.WriteLine("{0} {1}'s new income: {2:C}",
employee.GetType().Name, employee.Name,
employee.Income);

class President : Employee


{
// Constructor
public President()
: base("Dick", 45000.0, 21)
{
}
}

// Gets or sets number of vacation days


public int VacationDays
{
get { return _vacationDays; }
set { _vacationDays = value; }
}

}
}
/// <summary>
/// A 'ConcreteVisitor' class
/// </summary>
class VacationVisitor : IVisitor
{
public void Visit(Element element)
{
Employee employee = element as Employee;

/// The 'ObjectStructure' class


/// </summary>
class Employees
{
private List<Employee> _employees = new List<Employee>();

// Provide 3 extra vacation days


Console.WriteLine("{0} {1}'s new vacation days: {2}",
employee.GetType().Name, employee.Name,
employee.VacationDays);

}
public override void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
/// <summary>

ISGN - Confidential
www.isgn.com | p.15

Thank you

ISGN - Confidential
www.isgn.com | p.16

Anda mungkin juga menyukai