Strategy Pattern Pattern As Well As Opened Upwardly Unopen Regulation Inward Coffee - Example
Strategy pattern pattern is based upon opened upward unopen pattern principle, the 'O' of famous SOLID pattern principles. It's i of the pop pattern inward the champaign of object-oriented analysis in addition to pattern along amongst Decorator, Observer in addition to Factory patterns. Strategy pattern allows yous to encapsulate possible changes inward a procedure in addition to 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 pattern principle.
Though similar whatever other pattern pattern, it likewise introduces few to a greater extent than classes inward your codebase, but that's worth doing because it ameliorate organize your code in addition to provides much-needed flexibility. It likewise makes it slowly to alter attributes.
Strategy pattern is really useful, peculiarly for implementing algorithmic strategy e.g. encryption, compression, comparing etc. Influenza A virus subtype H5N1 distich of examples of Strategy pattern from JDK is Comparator in addition to LayoutManager. You tin sentiment Comparator every bit Strategy interface, define compare() method, right away 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 yous to organize components differently.
When nosotros say unopen for modification, it agency novel changes should endure implemented past times the novel code, rather than altering existing code. This reduces the possibility of breaking existing tried in addition to tested code.
The strategy pattern is likewise is i of the behavioral pattern inward GOF list, kickoff introduced inward classic GOF pattern pattern book.
In this example, we require to filter the Incoming message past times for sure criterion e.g. filter message if it's of a detail type. But yous know that this measure tin change, in addition to yous may require to filter the message past times their size or a specific keyword inward their content. In the centre of this operation, nosotros convey a filter() method inward a degree say MessageUtils, this degree is responsible for filtering messages.
In the simplest form, only removing them from incoming List of Messages. In social club to expire on this code intact fifty-fifty when filtering strategy changes due to novel requirements, nosotros volition utilization Strategy pattern 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 pattern makes it really slowly to innovate a novel strategy. We convey iii implementations of this Strategy interface FilterByType, FilterBySize, in addition to FilteryByKeyword.
Our information object Message contains a type, represented past times Java Enum, an integer size, in addition to String content. This pattern is likewise opened upward for extension, every bit yous tin innovate whatever 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, in addition to insertion sort.
You tin meet that our List contains 4 messages i of type XML in addition to iii of type TEXT. So when nosotros kickoff filter messages past times type XML, yous tin meet that alone the message amongst XML type is filtered. Next, when nosotros filter messages based upon keyword "Wrong", alone the message which contains this keyword are filtered.
Lastly, when I filtered messages on the size of 200, alone 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 pattern pattern.
You tin likewise utilization lambda expressions to implement Strategy pattern inward Java, every bit yous tin utilization lambdas inward house of anonymous class inward Java. This volition brand your code fifty-fifty to a greater extent than readable in addition to concise.
This degree is used to define dissimilar message types
This is the meat interface to define Strategy
This is i 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 i 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 pattern pattern inward Java. As I said, since Strategy pattern confirms opened upward unopen pattern principle, yous tin likewise sentiment this every bit an instance of Open Closed pattern regulation inward Java. Design patterns are tried in addition to tested way of solving work inward a detail context in addition to cognition of meat patterns actually helps yous to write ameliorate code. I strongly recommend Head First Object-Oriented Analysis in addition to Design and Head First Design Pattern book to every Java developer, both senior in addition to junior, who wants to acquire to a greater extent than nigh pattern pattern in addition to their effective utilization 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 pattern pattern, it likewise introduces few to a greater extent than classes inward your codebase, but that's worth doing because it ameliorate organize your code in addition to provides much-needed flexibility. It likewise makes it slowly to alter attributes.
Strategy pattern is really useful, peculiarly for implementing algorithmic strategy e.g. encryption, compression, comparing etc. Influenza A virus subtype H5N1 distich of examples of Strategy pattern from JDK is Comparator in addition to LayoutManager. You tin sentiment Comparator every bit Strategy interface, define compare() method, right away 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 yous to organize components differently.
Strategy pattern Pattern Example - Open Closed Design principle
This instance of Strategy pattern tin likewise endure seen every bit an instance of open unopen pattern principle, which states that a design, code (class or method) should rest opened upward for extension but unopen for modification.When nosotros say unopen for modification, it agency novel changes should endure implemented past times the novel code, rather than altering existing code. This reduces the possibility of breaking existing tried in addition to tested code.
The strategy pattern is likewise is i of the behavioral pattern inward GOF list, kickoff introduced inward classic GOF pattern pattern book.
In this example, we require to filter the Incoming message past times for sure criterion e.g. filter message if it's of a detail type. But yous know that this measure tin change, in addition to yous may require to filter the message past times their size or a specific keyword inward their content. In the centre of this operation, nosotros convey a filter() method inward a degree say MessageUtils, this degree is responsible for filtering messages.
In the simplest form, only removing them from incoming List of Messages. In social club to expire on this code intact fifty-fifty when filtering strategy changes due to novel requirements, nosotros volition utilization Strategy pattern 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 pattern makes it really slowly to innovate a novel strategy. We convey iii implementations of this Strategy interface FilterByType, FilterBySize, in addition to FilteryByKeyword.
Our information object Message contains a type, represented past times Java Enum, an integer size, in addition to String content. This pattern is likewise opened upward for extension, every bit yous tin innovate whatever 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, in addition to insertion sort.
Strategy pattern Pattern Implementation inward Java
Here is consummate code instance of Strategy pattern 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 pattern pattern * in addition to Open Closed pattern 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 pattern 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 pattern principle, * It's opened upward for modification, because * yous tin supply whatever filtering measure past times providing * implementation of FilteringStrategy, but * no require to alter whatever 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 pattern principle?}
You tin meet that our List contains 4 messages i of type XML in addition to iii of type TEXT. So when nosotros kickoff filter messages past times type XML, yous tin meet that alone the message amongst XML type is filtered. Next, when nosotros filter messages based upon keyword "Wrong", alone the message which contains this keyword are filtered.
Lastly, when I filtered messages on the size of 200, alone 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 pattern pattern.
You tin likewise utilization lambda expressions to implement Strategy pattern inward Java, every bit yous tin utilization lambdas inward house of anonymous class inward Java. This volition brand your code fifty-fifty to a greater extent than readable in addition to concise.
Important classes of this Example
Here are other of import classes to execute this instance :Message.java/* * Influenza A virus subtype H5N1 degree to correspond a Message amongst type, size in addition to 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 degree is used to define dissimilar message types
MessageType.java/* * Enum to announce dissimilar Message type */ public enum MessageType { TEXT, BYTE, XML; }
This is the meat interface to define Strategy
FilteringStrategy.java
/* * interface which defines Strategy for this pattern. */ public interface FilteringStrategy{ public boolean isFilterable(Message msg); }
This is i 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 i 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 pattern pattern inward Java. As I said, since Strategy pattern confirms opened upward unopen pattern principle, yous tin likewise sentiment this every bit an instance of Open Closed pattern regulation inward Java. Design patterns are tried in addition to tested way of solving work inward a detail context in addition to cognition of meat patterns actually helps yous to write ameliorate code. I strongly recommend Head First Object-Oriented Analysis in addition to Design and Head First Design Pattern book to every Java developer, both senior in addition to junior, who wants to acquire to a greater extent than nigh pattern pattern in addition to their effective utilization inward Java.
Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass
0 Response to "Strategy Pattern Pattern As Well As Opened Upwardly Unopen Regulation Inward Coffee - Example"
Post a Comment