DEV Community

Sarfraz Ahmed
Sarfraz Ahmed

Posted on • Originally published at codeinphp.github.io on

Strategy Design Pattern

In this post, we will explore what strategy design pattern is and what problems does it solve but first, what is a design pattern ? Here is how Wikipedia defines it:

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

So a design pattern is nothing but a re-usable solution towards commonly occurring problems you may face while programming.

Overview

One of the common problems we face in programming is to make decisions based on different conditions/inputs.

Let's say we have created a framework of our own and we want to be able to allow users to choose different types of logging methods such as logging to file, database or email.

Example

First, we create our logger classes for the framework that implement common interface:

interface InterfaceLogger {
    function log($message);
}

class FileLogger implements InterfaceLogger {
    public function log($message) {
        // code to write logging information to file system
    }   
}

class DatabaseLogger implements InterfaceLogger {
    public function log($message) {
        // code to write logging information to database
    }   
}

class EmailLogger implements InterfaceLogger {
    public function log($message) {
        // code to write logging information to email
    }   
}

Let's assume users of our framework are allowed to choose an specific logger through some configuration file by typing file, database or email and our framework is able to know it:

$loggerType = App::getConfig('logger');

Now we can easily find out which logger to use using strategy design pattern:

switch($loggerType) {
    case "file":
        $logger = new FileLogger();
        break;
    case "database":
        $logger = new DatabaseLogger();
        break;
    case "email":
        $logger = new EmailLogger();
        break;
    default:
        $logger = new FileLogger();
}

And then throughout our framework, we can use $logger->log() method which would automatically know which logger type to use.

As you might have noticed, strategy pattern is very simple one and we might have written similar code a number of times before albeit without realizing it is actually some design pattern.

Latest comments (0)