Strategy Design Pattern
In today’s blog and the upcoming ones we will be discussing about various design patterns. Officially there are 23 designs patterns.
First of all, what do you mean by design pattern ? A design pattern simply means an approach to solve any we face while developing any application.
People faced similar problems earlier and come up with 23 design patterns. Instead of reinventing the wheel we use these patterns whenever we we face some specific problem, which we will be discussing in depth.
Fundamentally all these design patterns says the same thing in different dfferent ways. In every application there will be two major parts, one part is that changes and the other part that doesn’t changes.
The main objective of these design patterns is to extract the dynamic part and make it a seeprate entity.
Introduction
strategy design pattern makes us realise that inheritance is bad. Let’s consider an example of an application thaat simulates robots
Ex:
- Let say we have a Robot class with two concrete methods walk() and talk(). walk() defines how different robots walk and talk() defines how they talk.
- we also have an abstract method projection which tells us how the robots look like.
- So we can clearly inherit the Robot class with Companion R and Worker R. There is no problem in it.
Let’s say now a new type of robots came which can fly
Ex:
- But the problem is for every new type of robots that can fly we have to write the fly() method logic again and again.
- So let’s increase the inehritance hierarchy to solve this problem.
Ex:
Problem: Suppose a new type of flying robots comes which flies using jets. To solve this problem we again have to increase the ineheritance hierarchy.
Get Irfan’s stories in your inbox
Join Medium for free to get updates from this writer.
Ex:
The problem will keep on rising if different types of robot comes.
NOTE: THe solution to inheritance should not be more inheritance.
To solve this type of problem we use Strategy design pattern. Strategy Design pattern defines a family of algoritm, puts them into seperate classes so that they can be changed at runtime.
Ex: The above situation can be perfectly depicted using the below UML digram. Instead of using only inheritance we will be uisng composition.
- In the above diagram if different robots shows projection differently for different then again we will face the same problem.
- So we can make a seperate abstract class Projectable and inherit it to NormalProjection and NoProjection and proceed accordingly.
Implementaion
from abc import ABC, abstractmethod
# --- Strategy Interface for Walk ---
class WalkableRobot(ABC):
@abstractmethod
def walk(self):
pass
# --- Concrete Strategies for walk ---
class NormalWalk(WalkableRobot):
def walk(self):
print("Walking normally...")
class NoWalk(WalkableRobot):
def walk(self):
print("Cannot walk.")
# --- Strategy Interface for Talk ---
class TalkableRobot(ABC):
@abstractmethod
def talk(self):
pass
# --- Concrete Strategies for Talk ---
class NormalTalk(TalkableRobot):
def talk(self):
print("Talking normally...")
class NoTalk(TalkableRobot):
def talk(self):
print("Cannot talk.")
# --- Strategy Interface for Fly ---
class FlyableRobot(ABC):
@abstractmethod
def fly(self):
pass
class NormalFly(FlyableRobot):
def fly(self):
print("Flying normally...")
class NoFly(FlyableRobot):
def fly(self):
print("Cannot fly.")
# --- Robot Base Class ---
class Robot(ABC):
def __init__(self, w: WalkableRobot, t: TalkableRobot, f: FlyableRobot):
self.__walkBehavior: WalkableRobot = w
self.__talkBehavior: TalkableRobot = t
self.__flyBehavior: FlyableRobot = f
def walk(self):
self.__walkBehavior.walk()
def talk(self):
self.__talkBehavior.talk()
def fly(self):
self.__flyBehavior.fly()
@abstractmethod
def projection(self):
pass # Abstract method for subclasses
# --- Concrete Robot Types ---
class CompanionRobot(Robot):
def __init__(self, w: WalkableRobot, t: TalkableRobot, f: FlyableRobot):
super().__init__(w, t, f)
def projection(self):
print("Displaying friendly companion features...")
class WorkerRobot(Robot):
def __init__(self, w: WalkableRobot, t: TalkableRobot, f: FlyableRobot):
super().__init__(w, t, f)
def projection(self):
print("Displaying worker efficiency stats...")
# --- Main Function ---
if __name__ == "__main__":
robot1 = CompanionRobot(NormalWalk(), NormalTalk(), NoFly())
robot1.walk()
robot1.talk()
robot1.fly()
robot1.projection()
print("--------------------")
robot2 = WorkerRobot(NoWalk(), NoTalk(), NormalFly())
robot2.walk()
robot2.talk()
robot2.fly()
robot2.projection()Output
Walking normally...
Talking normally...
Cannot fly.
Displaying friendly companion features...
--------------------
Cannot walk.
Cannot talk.
Flying normally...
Displaying worker efficiency stats...Real Life Example
In payment systems we can pay with different ways, like w can use Credit Card, Debit Card, UPI, NEFT etc etc. In this we can use strategy design pattern.
Thank you for reading the blog. In our next blog we will be learning about Factory Design Pattern.
Credits: Aditya Tandon






