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
- First create an interface with required abstract methods
- Implement the above created interface by a class
- Pass an object of your required implementing class where ever you want to use it
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
Post a Comment
Post a Comment