DEV Community

Ahmad Ibrahim
Ahmad Ibrahim

Posted on

Strategy Pattern Basic Example

The strategy pattern is used when a job can be done using different algorithms (strategies), and we need the ability to change the execution strategy dynamically and without changing the API that we're calling. Consider sorting an array of elements, where we have multiple sort algorithms (bubble sort, quick sort, etc..).

Let's take an example of a traveler who can move from city to city using different means of transport (car, plane, bus, etc..). We might make a Traveler class like this.

class Traveler
{
   public void TravelByCar()
   {
       // implementation
   }
   public void TravelByPlane()
   {
       // implementation
   }
   public void TravelByBus()
   {
       // implementation
   }
}
Enter fullscreen mode Exit fullscreen mode

There are some problems with the above code, firstly it violates the Open/Closed principle, as you have to modify the Traveler class whenever you need to add another means of transport, secondly, we introduce a different API for each transport which forces the caller to specify the API whenever he uses it (maybe he's not concerned with this transport details).
The strategy pattern solves this problems by separating the travel strategy from the traveler as follow.

class Traveler
{
    private ITransport _transport;

    public Traveler(ITransporter defaultTransport)
    {
        _transport = defaultTransport;
    }

    public void Travel()
    {
        _transport.Move();
    }

    public void ChangeTransport(ITransport newTransport)
    {
        _transport = newTransport;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now the API caller will provide a default strategy only at constructing the object and he will simply call one API afterwards.

var traveler = new Traveler(new BusTransport());  // pass the default strategy

traveler.Travel();    // use just a single API to travel
Enter fullscreen mode Exit fullscreen mode

The API user can also change the strategy without having to modify the existing class.

var transport = new CarTrasnport();
traveler.ChangeTransport(transport);
Enter fullscreen mode Exit fullscreen mode

He can also introduce new transports.

class TrainTransport : ITransport
{
    // transport implementation
}

... 

var transport = new TrainTransport();
traveler.ChangeTransport(transport);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)