Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Gauge for SharePoint
Search :       Advanced Search »
Home » Design & Architecture » Design Patterns (Strategy Pattern) Part - II

Design Patterns (Strategy Pattern) Part - II

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Page Views : 4540
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Gauge for SharePoint
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction
 
As we all have a brief idea of what design patterns and what role it plays in the Software Development Life Cycle. Now we will look into one of the most important pattern known as "Strategy Pattern". Lets start up with an example.

In this Article we will also use the following design principles:

  • Identify the aspects of your application that vary and separate them from what stays the same.
  • Program to an interface, not an implementation
  • Favor Composition over inheritance

Problem (WorldCarSimulator)



A simulator which demonstrates the types of worldwide cars and their features. Users can choose any type of cars, then the simulator should give a demonstration of the type of car selected with the features available for that car.
 
Start with the basic design
 
Consider the following basic design:
 
 

Here Car is the base class. Taxi and RentedCar's are the derived classes.

Carry() is defined in base class and run() is overridden in the derived classes as required.

Suddenly you recognise that, as this is for worldwide cars, there are some cars, which go for race. 
 

 
Only change required is to add a race() method in the base class so some cars can go for the race.
 
Update the code with race() method and now the code is ready for demo.
 
User starts the Demo, Some thing went horribly wrong.

"Taxi's started racing"
"RaceCar's started carrying passengers"

Now code needs to be modified.

Modify Taxi Class

  • Race() to do nothing

Modify RaceCar Class

  • Carry() to do nothing

Consider about ToyCar they do not race nor they do not Carry.
 
Create the ToyCar Class

  • Race() to do nothing
  • Carry() to do nothing

 

As long as new type of car's come, the more modification is required. Let us think about some alternative solution like the following below.
 
 

In the above design, there is no reusability. As long as you add classes you need to override the methods carry() or race() etc. so this is not a good design.
 
Let us use Design Principle one:

"Identify the aspects of your application that vary and separate them from what stays the same"

 

Like this :
 
And one more thing we are using classes where in we do not have a chance for dynamic behaviour. Ie... for example Taxi started taking passengers and after some time it want to go for a race, which is not possible as per the last design.
 
Ok. Lets implement the second design principle:

"Program to an interface, not an implementation"

Let see the design now using the two principles:
 

 
We just had designed for the behaviour of Car's like Carry, Race etc..
 
Now we need to design the Types of Cars. It's now time to use the third principle.

"Favor Composition over inheritance"

Here is the final design:
 


At last we had implemented the first design pattern
 
"Strategy Pattern"

"Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."

Now the code walk through:
 
Car Class

Public abstract class Car
{
CarryBehaviour carryBehaviour;
RaceBehaviour raceBehaviour;
public Car()
{
}
public abstract void run();
public void race()
{
raceBehaviour.race();
}
public void carry()
{
carryBehaviour.carry();
}
public void setraceBehaviour(RaceBehaviour rb)
{
raceBehaviour = rb;
}
public void setcarryBehaviour(CarryBehaviour cb)
{
carryBehaviour = cb;
}
}

RaceBehaviour (Interface), RaceCar (Class) & RaceNoWay (Class):
 
public interface RaceBehaviour
{
public void race();
}
public class RaceCar implements RaceBehaviour
{
public void race()
{
system.
out.println("I am racing");
}
}
public class RaceNoWay implements RaceBehaviour
{
public void race()
{
system.
out.println("I can't race");
}
}
 
 
CarBehaviour (Interface), CarryPeople (Class) , NonCarrier (Class) & CarryLoad (Class):
 
public interface CarryBehaviour
{
public void carry();
}
public class CarryPeople implements CarryBehaviour
{
public void carry()
{
system.
out.println("I can carry only people");
}
}
public class NonCarrier implements CarryBehaviour
{
public void carry()
{
system.
out.println("I can't carry");
}
}
public class CarryLoad implements CarryBehaviour
{
public void carry()
{
system.
out.println("I can carry only Load");
}
}

 
Car Class
 
Public class Taxi extends Car
{
public Taxi()
{
carryBehaviour =
new CarryPeople();
raceBehaviour =
new RaceNoWay();
}
public void run()
{
System.
out.println("Running a Taxi");
}
}

Jeep Class
 
Public class Jeep extends Car
{
public Taxi()
{
carryBehaviour =
new CarryLoad();
raceBehaviour =
new RaceNoWay();
}
public void run()
{
System.
out.println("Running a Jeep");
}
}

 
RaceCar Class
 
Public class RaceCar extends Car
{
public Taxi()
{
carryBehaviour =
new NonCarrier();
raceBehaviour =
new RaceCar();
}
public void run()
{
System.
out.println("Going for Race");
}
}
 
 
ToyCar Class
 
Public class ToyCar extends Car
{
public Taxi()
{
carryBehaviour =
new NonCarrier();
raceBehaviour =
new RaceNoWay();
}
public void run()
{
System.
out.println("Play with ToyCar ");
}
}

RentalCar Class
 
Public class RentalCar extends Car
{
public Taxi()
{
carryBehaviour =
new CarryPeople();
raceBehaviour =
new RaceNoWay();
}
public void run()
{
System.
out.println("I am Rented Car");
}
}
 
 
Small Demo
 
Public class WorldCarSimulator
{
public static void main(string[] args)
{
Car Ferrari =
new RaceCar();
Ferrari.carry();
Ferrari.race();
Ferrari.run();
Car RoadRunnerTaxi =
new Taxi();
RoadRunnerTaxi.carry();
RoadRunnerTaxi.race();
//Changing the behaviour dynamically
RoadRunnerTaxi.setraceBehaviour(new RaceBehaviour());
RoadRunnerTaxi.race();
}
}

 
Strategy Pattern Explained
 

  
Participants 
 
The classes and/or objects participating in this pattern are:

  • Strategy (SortStrategy)
    • declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy 
  • ConcreteStrategy (QuickSort, ShellSort, MergeSort)
    • implements the algorithm using the Strategy interface
  • Context (SortedList) 
    • is configured with a ConcreteStrategy object
    • maintains a reference to a Strategy object 
    • may define an interface that lets Strategy access its data.
  • Observer (IInvestor)
    • defines an updating interface for objects that should be notified of changes in a subject. 
  • ConcreteObserver (Investor)
    • maintains a reference to a ConcreteSubject object
    • stores state that should stay consistent with the subject's
    • implements the Observer updating interface to keep its state consistent with the subject's

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Saif Ikram
Saif Ikram is a Software Consultant and an Associate Member of WWISA having 6+ years of IT Experience. He has been involved in designing several .NET projects and has extensive experience in designing and implementing Windows & Web based Applications. He holds a Masters degree in Computer Applications, and is a Microsoft Certified Professional. He works for Genisys Software and is currently deputed to Royal Bank of Scotland,London.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.