Strategy blueprint pattern is based upon opened upward unopen blueprint principle, the 'O' of famous SOLID blueprint principles. It's 1 of the pop pattern inward the champaign of object-oriented analysis together with blueprint along alongside Decorator, Observer together with Factory patterns. Strategy pattern allows you lot to encapsulate possible changes inward a procedure together with encapsulate that inward a Strategy class. By doing that your procedure (mainly a method) depends upon a strategy, higher flat of abstraction than implementation. This makes your procedure opened upward for extension past times providing novel Strategy implementation, but unopen for modification, because the introduction of a novel strategy doesn't require a alter inward a tested method. That's how it confirms open unopen blueprint principle.
Though similar whatever other blueprint pattern, it too introduces few to a greater extent than classes inward your codebase, but that's worth doing because it improve organize your code together with provides much-needed flexibility. It too makes it slow to alter attributes.
Strategy pattern is rattling useful, peculiarly for implementing algorithmic strategy e.g. encryption, compression, comparing etc. H5N1 pair of examples of Strategy pattern from JDK is Comparator together with LayoutManager. You tin sentiment Comparator every bit Strategy interface, define compare() method, at 1 time it's upward to the classes how they compare themselves.
This method is utilized for sorting within Collections.sort(), which confirms OCP because it doesn't require whatever alter when comparing logic changes. Similarly LayoutManager e.g. GridLayout, BorderLayout helps you lot to organize components differently.
When nosotros say unopen for modification, it way novel changes should locomote implemented past times the novel code, rather than altering existing code. This reduces the possibility of breaking existing tried together with tested code.
The strategy pattern is too is 1 of the behavioral pattern inward GOF list, showtime introduced inward classic GOF blueprint pattern book.
In this example, we require to filter the Incoming message past times certainly criterion e.g. filter message if it's of a item type. But you lot know that this touchstone tin change, together with you lot may require to filter the message past times their size or a specific keyword inward their content. In the centre of this operation, nosotros accept a filter() method inward a flat say MessageUtils, this flat is responsible for filtering messages.
In the simplest form, merely removing them from incoming List of Messages. In lodge to buy the farm on this code intact fifty-fifty when filtering strategy changes due to novel requirements, nosotros volition usage Strategy blueprint pattern.
In lodge to Strategy pattern, nosotros volition define a Strategy interface say FilteringStrategy which contains isFilterable(Message msg) method, this method returns truthful if Message passed to it is filterable past times criteria, implemented past times subclasses.
This blueprint makes it rattling slow to innovate a novel strategy. We accept 3 implementations of this Strategy interface FilterByType, FilterBySize, together with FilteryByKeyword.
Our information object Message contains a type, represented past times Java Enum, an integer size, together with String content. This blueprint is too opened upward for extension, every bit you lot tin innovate whatever filtering strategy.
Here is UML diagram of Strategy pattern, this time, nosotros are using sorting strategy to implement unlike sorting algorithms e.g. bubble sort, quick sort, together with insertion sort.
You tin meet that our List contains iv messages 1 of type XML together with 3 of type TEXT. So when nosotros showtime filter messages past times type XML, you lot tin meet that solely the message alongside XML type is filtered. Next, when nosotros filter messages based upon keyword "Wrong", solely the message which contains this keyword are filtered.
Lastly, when I filtered messages on the size of 200, solely the message whose size is greater than 200 are filtered. So nosotros tin exercise unlike things from same code past times merely providing a novel implementation of Strategy interface, this is the ability of Strategy blueprint pattern.
You tin too usage lambda expressions to implement Strategy pattern inward Java, every bit you lot tin usage lambdas inward house of anonymous class inward Java. This volition brand your code fifty-fifty to a greater extent than readable together with concise.
This flat is used to define unlike message types
This is the center interface to define Strategy
This is 1 implementation of Strategy interface, which filters messages past times their type.
Here is approximately other implementation of Strategy interface which filters messages past times size :
Here is 1 to a greater extent than implementation of Strategy interface which volition filter messages past times keywords
That's all inward this real life event of Strategy blueprint pattern inward Java. As I said, since Strategy pattern confirms opened upward unopen blueprint principle, you lot tin too sentiment this every bit an event of Open Closed blueprint regulation inward Java. Design patterns are tried together with tested way of solving occupation inward a item context together with cognition of center patterns actually helps you lot to write improve code. I strongly recommend Head First Object-Oriented Analysis together with Design and Head First Design Pattern book to every Java developer, both senior together with junior, who wants to acquire to a greater extent than most blueprint pattern together with their effective usage inward Java.
Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass
Though similar whatever other blueprint pattern, it too introduces few to a greater extent than classes inward your codebase, but that's worth doing because it improve organize your code together with provides much-needed flexibility. It too makes it slow to alter attributes.
Strategy pattern is rattling useful, peculiarly for implementing algorithmic strategy e.g. encryption, compression, comparing etc. H5N1 pair of examples of Strategy pattern from JDK is Comparator together with LayoutManager. You tin sentiment Comparator every bit Strategy interface, define compare() method, at 1 time it's upward to the classes how they compare themselves.
This method is utilized for sorting within Collections.sort(), which confirms OCP because it doesn't require whatever alter when comparing logic changes. Similarly LayoutManager e.g. GridLayout, BorderLayout helps you lot to organize components differently.
Strategy blueprint Pattern Example - Open Closed Design principle
This event of Strategy pattern tin too locomote seen every bit an event of open unopen blueprint principle, which states that a design, code (class or method) should stay opened upward for extension but unopen for modification.When nosotros say unopen for modification, it way novel changes should locomote implemented past times the novel code, rather than altering existing code. This reduces the possibility of breaking existing tried together with tested code.
The strategy pattern is too is 1 of the behavioral pattern inward GOF list, showtime introduced inward classic GOF blueprint pattern book.
In this example, we require to filter the Incoming message past times certainly criterion e.g. filter message if it's of a item type. But you lot know that this touchstone tin change, together with you lot may require to filter the message past times their size or a specific keyword inward their content. In the centre of this operation, nosotros accept a filter() method inward a flat say MessageUtils, this flat is responsible for filtering messages.
In the simplest form, merely removing them from incoming List of Messages. In lodge to buy the farm on this code intact fifty-fifty when filtering strategy changes due to novel requirements, nosotros volition usage Strategy blueprint pattern.
In lodge to Strategy pattern, nosotros volition define a Strategy interface say FilteringStrategy which contains isFilterable(Message msg) method, this method returns truthful if Message passed to it is filterable past times criteria, implemented past times subclasses.
This blueprint makes it rattling slow to innovate a novel strategy. We accept 3 implementations of this Strategy interface FilterByType, FilterBySize, together with FilteryByKeyword.
Our information object Message contains a type, represented past times Java Enum, an integer size, together with String content. This blueprint is too opened upward for extension, every bit you lot tin innovate whatever filtering strategy.
Here is UML diagram of Strategy pattern, this time, nosotros are using sorting strategy to implement unlike sorting algorithms e.g. bubble sort, quick sort, together with insertion sort.
Strategy blueprint Pattern Implementation inward Java
Here is consummate code event of Strategy blueprint pattern inward Java.import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Java plan to implement Strategy blueprint pattern * together with Open Closed blueprint principle. * filter() method uses Strategy pattern to filter messages. * * @author Javin Paul */ public class StrategyPattern { private static final Logger logger = LoggerFactory.getLogger(StrategyPattern.class); public static void main(String args[]) { List<Message> messages = new ArrayList<>(); messages.add(new Message(MessageType.TEXT, 100, "This is assay message")); messages.add(new Message(MessageType.XML, 200, "How are you lot ")); messages.add(new Message(MessageType.TEXT, 300, "Does Strategy pattern follows OCP blueprint principle?")); messages.add(new Message(MessageType.TEXT, 400, "Wrong Message, should locomote filtered")); messages = filter(messages, new FilterByType(MessageType.XML)); messages = filter(messages, new FilterByKeyword("Wrong")); messages = filter(messages, new FilterBySize(200)); } /* * This method confirms Open Closed blueprint principle, * It's opened upward for modification, because * you lot tin render whatever filtering touchstone past times providing * implementation of FilteringStrategy, but * no require to alter whatever code here. * New functionality volition locomote provided past times novel code. */ public static final List<Message> filter(List<Message> messageList, FilteringStrategy strategy){ Iterator<Message> itr = messageList.iterator(); while(itr.hasNext()){ Message msg = itr.next(); if(strategy.isFilterable(msg)){ logger.info(strategy.toString() + msg); itr.remove(); } } return messageList; } } Output: - Filtering By type: XML Message{type=XML, size=200, content=<data>How are you lot </data>} - Filtering By keyword: Wrong Message{type=TEXT, size=400, content=Wrong Message, should locomote filtered} - Filtering By maxSize: 200 Message{type=TEXT, size=300, content=Does Strategy pattern follows OCP blueprint principle?}
You tin meet that our List contains iv messages 1 of type XML together with 3 of type TEXT. So when nosotros showtime filter messages past times type XML, you lot tin meet that solely the message alongside XML type is filtered. Next, when nosotros filter messages based upon keyword "Wrong", solely the message which contains this keyword are filtered.
Lastly, when I filtered messages on the size of 200, solely the message whose size is greater than 200 are filtered. So nosotros tin exercise unlike things from same code past times merely providing a novel implementation of Strategy interface, this is the ability of Strategy blueprint pattern.
You tin too usage lambda expressions to implement Strategy pattern inward Java, every bit you lot tin usage lambdas inward house of anonymous class inward Java. This volition brand your code fifty-fifty to a greater extent than readable together with concise.
Important classes of this Example
Here are other of import classes to execute this event :Message.java/* * H5N1 flat to stand upward for a Message alongside type, size together with content */ class Message{ private MessageType type; private int size; private String content; public Message(MessageType type, int size, String content) { this.type = type; this.size = size; this.content = content; } public String getContent() { return content; } public int getSize() { return size; } public MessageType getType() { return type; } @Override public String toString() { return " Message{" + "type=" + type + ", size=" + size + ", content=" + content + '}'; } }
This flat is used to define unlike message types
MessageType.java/* * Enum to announce unlike Message type */ public enum MessageType { TEXT, BYTE, XML; }
This is the center interface to define Strategy
FilteringStrategy.java
/* * interface which defines Strategy for this pattern. */ public interface FilteringStrategy{ public boolean isFilterable(Message msg); }
This is 1 implementation of Strategy interface, which filters messages past times their type.
FilterByType.java/* * An implementation of Strategy interface, which decides to filter * message past times type. */ public class FilterByType implements FilteringStrategy{ private MessageType type; public FilterByType(MessageType type) { this.type = type; } @Override public boolean isFilterable(Message msg) { return type == msg.getType(); } @Override public String toString() { return "Filtering By type: " + type; } }
Here is approximately other implementation of Strategy interface which filters messages past times size :
FilterBySize.java/* * Another Strategy implementation for filtering message past times size */ public class FilterBySize implements FilteringStrategy{ private int maxSize; public FilterBySize(int maxSize) { this.maxSize = maxSize; } @Override public boolean isFilterable(Message msg) { return msg.getSize() > maxSize; } @Override public String toString() { return "Filtering By maxSize: " + maxSize; } }
Here is 1 to a greater extent than implementation of Strategy interface which volition filter messages past times keywords
FilterByKeyword.java/* * Another Strategy implementation for filtering message past times keyword inward content. */ public class FilterByKeyword implements FilteringStrategy{ private String keyword; public FilterByKeyword(String keyword) { this.keyword = keyword; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } @Override public boolean isFilterable(Message msg) { return msg.getContent()==null || msg.getContent().contains(keyword); } @Override public String toString() { return "Filtering By keyword: " + keyword; } }
That's all inward this real life event of Strategy blueprint pattern inward Java. As I said, since Strategy pattern confirms opened upward unopen blueprint principle, you lot tin too sentiment this every bit an event of Open Closed blueprint regulation inward Java. Design patterns are tried together with tested way of solving occupation inward a item context together with cognition of center patterns actually helps you lot to write improve code. I strongly recommend Head First Object-Oriented Analysis together with Design and Head First Design Pattern book to every Java developer, both senior together with junior, who wants to acquire to a greater extent than most blueprint pattern together with their effective usage inward Java.
Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass