Strategy Blueprint Pattern In Addition To Opened Upward Unopen Regulation Inward Coffee - Example
Strategy blueprint pattern is based upon opened upwards unopen blueprint principle, the 'O' of famous SOLID blueprint principles. It's ane of the pop pattern inward the plain of object-oriented analysis as well as blueprint along amongst Decorator, Observer as well as Factory patterns. Strategy pattern allows yous to encapsulate possible changes inward a procedure as well as 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 upwards 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 whatsoever other blueprint pattern, it every bit good introduces few to a greater extent than classes inward your codebase, but that's worth doing because it meliorate organize your code as well as provides much-needed flexibility. It every bit good makes it slow to alter attributes.
Strategy pattern is real useful, peculiarly for implementing algorithmic strategy e.g. encryption, compression, comparing etc. H5N1 brace of examples of Strategy pattern from JDK is Comparator as well as LayoutManager. You tin sentiment Comparator every bit Strategy interface, define compare() method, straightaway it's upwards to the classes how they compare themselves.
This method is utilized for sorting within Collections.sort(), which confirms OCP because it doesn't require whatsoever alter when comparing logic changes. Similarly LayoutManager e.g. GridLayout, BorderLayout helps yous to organize components differently.
When nosotros say unopen for modification, it way novel changes should endure implemented past times the novel code, rather than altering existing code. This reduces the possibility of breaking existing tried as well as tested code.
The strategy pattern is every bit good is ane of the behavioral pattern inward GOF list, start introduced inward classic GOF blueprint pattern book.
In this example, we postulate to filter the Incoming message past times sure as shooting criterion e.g. filter message if it's of a item type. But yous know that this measure tin change, as well as yous may postulate to filter the message past times their size or a specific keyword inward their content. In the oculus of this operation, nosotros bring a filter() method inward a flat say MessageUtils, this flat is responsible for filtering messages.
In the simplest form, only removing them from incoming List of Messages. In social club to continue this code intact fifty-fifty when filtering strategy changes due to novel requirements, nosotros volition usage Strategy blueprint pattern.
In social club 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 real slow to innovate a novel strategy. We bring iii implementations of this Strategy interface FilterByType, FilterBySize, as well as FilteryByKeyword.
Our information object Message contains a type, represented past times Java Enum, an integer size, as well as String content. This blueprint is every bit good opened upwards for extension, every bit yous tin innovate whatsoever filtering strategy.
Here is UML diagram of Strategy pattern, this time, nosotros are using sorting strategy to implement dissimilar sorting algorithms e.g. bubble sort, quick sort, as well as insertion sort.
You tin meet that our List contains 4 messages ane of type XML as well as iii of type TEXT. So when nosotros start filter messages past times type XML, yous tin meet that exclusively the message amongst XML type is filtered. Next, when nosotros filter messages based upon keyword "Wrong", exclusively the message which contains this keyword are filtered.
Lastly, when I filtered messages on the size of 200, exclusively the message whose size is greater than 200 are filtered. So nosotros tin practice dissimilar things from same code past times only providing a novel implementation of Strategy interface, this is the ability of Strategy blueprint pattern.
You tin every bit good usage lambda expressions to implement Strategy pattern inward Java, every bit yous tin usage lambdas inward house of anonymous class inward Java. This volition brand your code fifty-fifty to a greater extent than readable as well as concise.
This flat is used to define dissimilar message types
This is the marrow interface to define Strategy
This is ane implementation of Strategy interface, which filters messages past times their type.
Here is roughly other implementation of Strategy interface which filters messages past times size :
Here is ane to a greater extent than implementation of Strategy interface which volition filter messages past times keywords
That's all inward this real life instance of Strategy blueprint pattern inward Java. As I said, since Strategy pattern confirms opened upwards unopen blueprint principle, yous tin every bit good sentiment this every bit an instance of Open Closed blueprint regulation inward Java. Design patterns are tried as well as tested way of solving work inward a item context as well as noesis of marrow patterns actually helps yous to write meliorate code. I strongly recommend Head First Object-Oriented Analysis as well as Design and Head First Design Pattern book to every Java developer, both senior as well as junior, who wants to larn to a greater extent than almost blueprint pattern as well as 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 whatsoever other blueprint pattern, it every bit good introduces few to a greater extent than classes inward your codebase, but that's worth doing because it meliorate organize your code as well as provides much-needed flexibility. It every bit good makes it slow to alter attributes.
Strategy pattern is real useful, peculiarly for implementing algorithmic strategy e.g. encryption, compression, comparing etc. H5N1 brace of examples of Strategy pattern from JDK is Comparator as well as LayoutManager. You tin sentiment Comparator every bit Strategy interface, define compare() method, straightaway it's upwards to the classes how they compare themselves.
This method is utilized for sorting within Collections.sort(), which confirms OCP because it doesn't require whatsoever alter when comparing logic changes. Similarly LayoutManager e.g. GridLayout, BorderLayout helps yous to organize components differently.
Strategy blueprint Pattern Example - Open Closed Design principle
This instance of Strategy pattern tin every bit good endure seen every bit an instance of open unopen blueprint principle, which states that a design, code (class or method) should rest opened upwards for extension but unopen for modification.When nosotros say unopen for modification, it way novel changes should endure implemented past times the novel code, rather than altering existing code. This reduces the possibility of breaking existing tried as well as tested code.
The strategy pattern is every bit good is ane of the behavioral pattern inward GOF list, start introduced inward classic GOF blueprint pattern book.
In this example, we postulate to filter the Incoming message past times sure as shooting criterion e.g. filter message if it's of a item type. But yous know that this measure tin change, as well as yous may postulate to filter the message past times their size or a specific keyword inward their content. In the oculus of this operation, nosotros bring a filter() method inward a flat say MessageUtils, this flat is responsible for filtering messages.
In the simplest form, only removing them from incoming List of Messages. In social club to continue this code intact fifty-fifty when filtering strategy changes due to novel requirements, nosotros volition usage Strategy blueprint pattern.
In social club 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 real slow to innovate a novel strategy. We bring iii implementations of this Strategy interface FilterByType, FilterBySize, as well as FilteryByKeyword.
Our information object Message contains a type, represented past times Java Enum, an integer size, as well as String content. This blueprint is every bit good opened upwards for extension, every bit yous tin innovate whatsoever filtering strategy.
Here is UML diagram of Strategy pattern, this time, nosotros are using sorting strategy to implement dissimilar sorting algorithms e.g. bubble sort, quick sort, as well as insertion sort.
Strategy blueprint Pattern Implementation inward Java
Here is consummate code instance 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 * as well as 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 essay message")); messages.add(new Message(MessageType.XML, 200, "How are yous ")); messages.add(new Message(MessageType.TEXT, 300, "Does Strategy pattern follows OCP blueprint principle?")); messages.add(new Message(MessageType.TEXT, 400, "Wrong Message, should endure 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 upwards for modification, because * yous tin render whatsoever filtering measure past times providing * implementation of FilteringStrategy, but * no postulate to alter whatsoever code here. * New functionality volition endure 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 yous </data>} - Filtering By keyword: Wrong Message{type=TEXT, size=400, content=Wrong Message, should endure 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 4 messages ane of type XML as well as iii of type TEXT. So when nosotros start filter messages past times type XML, yous tin meet that exclusively the message amongst XML type is filtered. Next, when nosotros filter messages based upon keyword "Wrong", exclusively the message which contains this keyword are filtered.
Lastly, when I filtered messages on the size of 200, exclusively the message whose size is greater than 200 are filtered. So nosotros tin practice dissimilar things from same code past times only providing a novel implementation of Strategy interface, this is the ability of Strategy blueprint pattern.
You tin every bit good usage lambda expressions to implement Strategy pattern inward Java, every bit yous tin usage lambdas inward house of anonymous class inward Java. This volition brand your code fifty-fifty to a greater extent than readable as well as concise.
Important classes of this Example
Here are other of import classes to execute this instance :Message.java/* * H5N1 flat to stand upwards for a Message amongst type, size as well as 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 dissimilar message types
MessageType.java/* * Enum to announce dissimilar Message type */ public enum MessageType { TEXT, BYTE, XML; }
This is the marrow interface to define Strategy
FilteringStrategy.java
/* * interface which defines Strategy for this pattern. */ public interface FilteringStrategy{ public boolean isFilterable(Message msg); }
This is ane 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 roughly 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 ane 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 instance of Strategy blueprint pattern inward Java. As I said, since Strategy pattern confirms opened upwards unopen blueprint principle, yous tin every bit good sentiment this every bit an instance of Open Closed blueprint regulation inward Java. Design patterns are tried as well as tested way of solving work inward a item context as well as noesis of marrow patterns actually helps yous to write meliorate code. I strongly recommend Head First Object-Oriented Analysis as well as Design and Head First Design Pattern book to every Java developer, both senior as well as junior, who wants to larn to a greater extent than almost blueprint pattern as well as 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


Komentar
Posting Komentar