SEARCH BY

All

  • All
  • Java8
  • Spring

Strategy Design Pattern in Java

Post a Comment

Introduction

Strategy Design Pattern is one type of Behavioural design pattern in java. Strategy pattern let the customer to pick/use algorithm to use from available multiple algorithms perform same action.
If you have an idea about interfaces concept in java, then you can understand strategy pattern easily. What we know about interfaces, we can create interface and then we can implement that interface by one class or more than one class. So if interface implemented by more than one class then client has a freedom to choose which implementing class to be used in their application. This type of application design called as strategy pattern or policy design pattern

How to implement Strategy pattern

First we must identify the situation to implement by strategy pattern. If there is a need to provide different possibilities for same type of action/algorithm then we need to implement that functionality based on strategy pattern.
Instead of writing different methods for different algorithms in a same class,  we can create one class for each algorithm where code maintenance and upgrading will be more easy.
In this article algorithm means nothing but a logic of action like adding, sorting, filtering etc...

Steps to implement strategy pattern

  1. First create an interface with required abstract methods
  2. Implement the above created interface by a class
  3. Pass an object of your required implementing class where ever you want to use it
For better understating about strategy pattern we can see Comparator interface in java. Comparator interface can be provided as a parameter to Collections.sort(List L, Comparator com)
Let us consider there is a list of Students, now we can create two sorting classes one is for sorting by student ID named as SortingByID and another one is sorting by student name named as SortingByName . These two sorting classes are implementing classes of Comparator interface by implementing compare(Strung s1, Student s2) method. So as per the sorting need of students list client can pass SortingByID class or SortingByName class as a parameter to Collections.sort() method
jaya
I love software designing, coding, writing and teaching...

Share this article

Related Posts

Post a Comment

Place your code in <em> </em> tags to send in comments | Do not add hyper links in commnet

Close

Subscribe our newsletter for the latest articles directly into your email inbox