stratergyPattern

Type of the pattern:

The Strategy Pattern is a behavioral design patterns (design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.)

Problem it solves:

Strategy pattern is based on the design principle ‘encapsulate what varies’, i.e. Identify the aspects of your application that vary and separate them from what stays the same.

The Strategy Pattern defines family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets algorithm vary independently from clients that use it.

Example:

Following class diagram shows hierarchy of different types of cellphone handsets developed by a company

stratergyPattern

But we have a problem here. Company decided to discontinue flashlight behavior from handset3. So the current design forced us to have a method stub which does nothing for handset3 flashlight behavior. So every time company comes up with a type of handset3 it has to take care of flashlight behavior and has to provide method stub for it.

 

Alternative approach can be to push flashlight behavior to handset1 and handset2 but then we end up adding duplicate code we have to maintain. Basically we violate a design principle “Do not repeat yourself”.

And things will become more complex as the company comes up with more handset types. This issue occurred because we tried to address change in behavior with inheritance and not composition. If we encapsulate flashlight and camera behavior in different classes and if Handset is a composition of camera and flashlight behavior it gives us more control over handset design. We can add/change behavior at runtime and come up with any number of designs without increasing number of classes we have to maintain. Below class diagram depicts this idea.

stratergyPattern1

 

 

 

 

 

 

 

code for flashlight behavior in CellPhones will be

public void setFlashLightBehaviour(FlashLightBehaviour flashLightBehaviour){

this. flashLightBehaviour = flashLightBehaviour

}

public void showFlashLight(){

flashLightBehaviour.turnOnFlashLight();

}

 

Strategy Pattern

Post navigation


Leave a Reply

Your email address will not be published. Required fields are marked *