Go Design Pattern — Strategy Method

Akhilesh Mahajan
2 min readSep 19, 2023

--

This article will discuss the Strategy Design Pattern Method ( a Behavioral Design pattern).

What happens in normal Inheritance is that a method defined by the base class can be used in its class (either the same logic or overrides the logic). But what if a method defined by one base class has to be used by another base class? 🧐

Right… 💁 We have to write duplicate code, which definitely is not a good practice.

Example

Consider the below diagram, here Vehivle factory is a Base class, which has a drive method Drive defined in it, which provides normal capability.

Now, there are three child classes, from the base class Vehicle Factory.
1. Ordinary Car
2. Sports Car
3. OffRoadCar

Ordinary Car -> Uses the same method as defined in the base class.
Sports Car -> Overrides the method to provide Speed Capability.
OffRoad Car → Also overrides the method to provide Speed capability.

Since Sports and offroad Cars override and implement the same method, there is code duplication. That’s where the strategy method comes in to resolve this code duplication.

Example

We define an interface for DriveStrategy which has the drive method implemented. We will define different drive capabilities as seen in the below code, which has the drive method implemented.

type DriveStrategy interface {
Drive(c *Car)
}

type NormalCapabilityStrategy struct{
}

func (nc * NormalCapabilityStrategy) Drive(c *Car){
// some logic
}

type SpeedCapabilityStrategy struct {

}

func (sc * SpeedCapabilityStrategy) Drive(c *Car){
// some logic
}

Now, we define a car struct, where we will create a method to get a car and initialize the DriveMethod with the object of drive strategies created above.

type Car struct{
DriveMethod *DriveStragey
}

func getCar(ds *DriveStrategy) *Car{
return &Car{
DriveMethod: ds
}
}

func (c *Car) Drive(){
c.DriveMethod.Drive(c)
}

Main function n will be like as below

func main(){

normalCapability := &NormalCapabilityStrategy{}
speedCapability := &SpeedCapabilityStrategy{}

ordinaryCar := getCar(normalCapability);
offRoadCar := getCar(speedCapability);

offRoadCar.Drive()
ordinaryCar.Drive()

}

Applicability:

  1. Use the Strategy pattern when you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime.
  2. Use the Strategy when you have a lot of similar classes that only differ in the way they execute some behavior.
  3. Use the pattern when your class has a massive conditional statement that switches between different variants of the same algorithm.
  4. Use the pattern to isolate the business logic of a class from the implementation details of algorithms that may not be as important in the context of that logic.

--

--