Tried to create the strategy pattern example as a vehicle that can fly or a drive on the road.
Intreastingly the
go method that is implemented in each of the vehicle sub classes is not hard coded into the subclass itself.
That means that a car go method is not very different from a helicopter go method. And here is the kicker: The method is not implemented in the car and vehicle classes.
The
go method is instead created in an interface.
So whats the big idea? We could as well create an interface and then implement it there.
ah but the interface is implemented in two classes GoDriving class and GoFlying class.
The abstract Vehicle class has a method that takes in an interface and decides what function to call. And then takes that interface and decides what
go method to call.
Its easy to understand because an interface in the Vehicle class is replced by the actual class(goFlying or goDriving is used) that implements that interface in the car class. Then the go method of
And all that is there in the car class is a call to GoDriving class to intantiate a variable.
The helicopter class therefore has only a call to GoFlying. This ensures that the
go method can be modified without modifying the Car and Helicopter classes.
The advantage becomes apparent when there is a huge number of classes and they may keep changing over time.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public interface goInterface
{
void goMethod();
}
class goDriving : goInterface
{
#region goInterface Members
void goInterface.goMethod()
{
System.Console.WriteLine("Go Driving");
}
#endregion
}
class goFlying : goInterface
{
#region goInterface Members
public void goMethod()
{
System.Console.WriteLine("Go Flying");
}
#endregion
}
public abstract class Vehicle : goInterface
{
public goInterface travelMode;
public void setTravelMode(goInterface x)
{
travelMode = x;
}
public void goMethod()
{
travelMode.goMethod();
}
}
public class Car : Vehicle
{
public Car()
{
goDriving drx = new goDriving();
setTravelMode(drx);
}
}
public class AeroPlane : Vehicle
{
}
class Program
{
static void Main(string[] args)
{
Car x = new Car();
x.goMethod();
System.Console.ReadLine();
}
}
}