DEV Community

Nima Akbarzadeh
Nima Akbarzadeh

Posted on • Updated on

Strategy design pattern in Python

Strategy Design Pattern in Python

If you are familiar with the basics of object-oriented programming, and its principles, and you use it on your projects, maybe it's time to start learning different design patterns and use them.

A good OO needs a good OO designer. The goal is we are trying to have a reusable, maintainable, and extensible code.
So you need a good design for OO. here's where design patterns come to help us!

There are lots of design patterns, you can find and read them in Gangs of Four (GoF) Design Patterns book.
Today we're going to talk about one of the easiest and most popular design patterns.

Strategy pattern is considered a behavioral design pattern.
It lets you define algorithms, put each of the algorithms into a separate class, and make your objects interchangeable.

For example, if you want to have an object and change its behavior, you need to modify the class code.
Imagine you have an OO-based calculator which just gets numbers and has setters, and you need to add new features and methods to it like summation, subtraction, multiplication, and division.

This time you are not going to implement these methods inside of class.

First of all, we need an abstract like this:

from abc import ABC, abstractmethod

class Operation_strategy(ABC):
    @abstractmethod
    def do_operation(self, n1, n2):
        pass
Enter fullscreen mode Exit fullscreen mode

After that, you need to generate new classes for each operation.

class Sum_strategy(Operation_strategy):
    def do_operation(self, n1, n2):
        return n1 + n2

class Sub_strategy(Operation_strategy):
    def do_operation(self, n1, n2):
        return n1 - n2

class Mul_strategy(Operation_strategy):
    def do_operation(self, n1, n2):
        return n1 * n2

class Div_strategy(Operation_strategy):
    def do_operation(self, n1, n2):
        if n2 != 0:
            result_number = n1 / n2
            return result_number
        else:
            raise ValueError("Sorry, no numbers below zero")
Enter fullscreen mode Exit fullscreen mode

Now one more thing, you have to init and set an operation setter inside your calculator class.

Maybe now you are confused and saying what's going on. But let me make it clear for you.

Inside of calculator class, instead of having 2 setters for numbers (first number and second number), we have 3 setters (first number, second number, operation).

The class does not have any idea of what is going to do, it just gets numbers and ALSO AN OPERATION!

With this pattern, you can easily define the behavior of your object without changing your class code, which is a clean way of coding because they are separated from each other.

You can see, download and run the full version of codes on my Github which make more sense. Here are the codes.

Also, this video can help you a lot.

Top comments (0)