Strategy Pattern Pattern In Addition To Opened Upwards Unopen Regulation Inwards Coffee - Example
Strategy blueprint pattern is based upon opened upward closed blueprint principle, the 'O' of famous SOLID blueprint principles. It's i of the pop pattern inwards the champaign of object-oriented analysis in addition to blueprint along amongst Decorator, Observer in addition to Factory patterns. Strategy pattern allows y'all to encapsulate possible changes inwards a procedure in addition to encapsulate that inwards 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 closed for modification, because the introduction of a novel strategy doesn't require a alter inwards a tested method. That's how it confirms open closed blueprint principle.
Though similar whatever other blueprint pattern, it besides introduces few to a greater extent than classes inwards your codebase, but that's worth doing because it meliorate organize your code in addition to provides much-needed flexibility. It besides makes it slow to alter attributes.
Strategy pattern is really useful, specially for implementing algorithmic strategy e.g. encryption, compression, comparing etc. Influenza A virus subtype H5N1 pair of examples of Strategy pattern from JDK is Comparator in addition to LayoutManager. You tin forcefulness out persuasion Comparator equally Strategy interface, define compare() method, similar a shot 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 y'all to organize components differently.
When nosotros say closed for modification, it agency novel changes should hold out 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 besides is i of the behavioral pattern inwards GOF list, commencement introduced inwards classic GOF blueprint pattern book.
In this example, we request to filter the Incoming message past times for sure criterion e.g. filter message if it's of a item type. But y'all know that this standard tin forcefulness out change, in addition to y'all may request to filter the message past times their size or a specific keyword inwards their content. In the catch of this operation, nosotros convey a filter() method inwards a flat say MessageUtils, this flat is responsible for filtering messages.
In the simplest form, only removing them from incoming List of Messages. In gild to give-up the ghost on this code intact fifty-fifty when filtering strategy changes due to novel requirements, nosotros volition usage Strategy blueprint pattern.
In gild 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 really slow to innovate a novel strategy. We convey 3 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 blueprint is besides opened upward for extension, equally y'all tin forcefulness out 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, in addition to insertion sort.
You tin forcefulness out run across that our List contains iv messages i of type XML in addition to 3 of type TEXT. So when nosotros commencement filter messages past times type XML, y'all tin forcefulness out run across 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 forcefulness out exercise unlike things from same code past times only providing a novel implementation of Strategy interface, this is the ability of Strategy blueprint pattern.
You tin forcefulness out besides usage lambda expressions to implement Strategy pattern inwards Java, equally y'all tin forcefulness out usage lambdas inwards house of anonymous class inwards Java. This volition brand your code fifty-fifty to a greater extent than readable in addition to concise.
This flat is used to define unlike message types
This is the total interface to define Strategy
This is i implementation of Strategy interface, which filters messages past times their type.
Here is closed to 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 inwards this real life instance of Strategy blueprint pattern inwards Java. As I said, since Strategy pattern confirms opened upward closed blueprint principle, y'all tin forcefulness out besides persuasion this equally an instance of Open Closed blueprint regulation inwards Java. Design patterns are tried in addition to tested way of solving employment inwards a item context in addition to noesis of total patterns actually helps y'all to write meliorate 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 larn to a greater extent than nigh blueprint pattern in addition to their effective usage inwards 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 besides introduces few to a greater extent than classes inwards your codebase, but that's worth doing because it meliorate organize your code in addition to provides much-needed flexibility. It besides makes it slow to alter attributes.
Strategy pattern is really useful, specially for implementing algorithmic strategy e.g. encryption, compression, comparing etc. Influenza A virus subtype H5N1 pair of examples of Strategy pattern from JDK is Comparator in addition to LayoutManager. You tin forcefulness out persuasion Comparator equally Strategy interface, define compare() method, similar a shot 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 y'all to organize components differently.
Strategy blueprint Pattern Example - Open Closed Design principle
This instance of Strategy pattern tin forcefulness out besides hold out seen equally an instance of open closed blueprint principle, which states that a design, code (class or method) should stay opened upward for extension but closed for modification.When nosotros say closed for modification, it agency novel changes should hold out 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 besides is i of the behavioral pattern inwards GOF list, commencement introduced inwards classic GOF blueprint pattern book.
In this example, we request to filter the Incoming message past times for sure criterion e.g. filter message if it's of a item type. But y'all know that this standard tin forcefulness out change, in addition to y'all may request to filter the message past times their size or a specific keyword inwards their content. In the catch of this operation, nosotros convey a filter() method inwards a flat say MessageUtils, this flat is responsible for filtering messages.
In the simplest form, only removing them from incoming List of Messages. In gild to give-up the ghost on this code intact fifty-fifty when filtering strategy changes due to novel requirements, nosotros volition usage Strategy blueprint pattern.
In gild 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 really slow to innovate a novel strategy. We convey 3 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 blueprint is besides opened upward for extension, equally y'all tin forcefulness out 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, in addition to insertion sort.
Strategy blueprint Pattern Implementation inwards Java
Here is consummate code instance of Strategy blueprint pattern inwards Java.import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Java programme to implement Strategy blueprint pattern * in addition to 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 attempt message")); messages.add(new Message(MessageType.XML, 200, "How are y'all ")); messages.add(new Message(MessageType.TEXT, 300, "Does Strategy pattern follows OCP blueprint principle?")); messages.add(new Message(MessageType.TEXT, 400, "Wrong Message, should hold out 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 * y'all tin forcefulness out supply whatever filtering standard past times providing * implementation of FilteringStrategy, but * no request to alter whatever code here. * New functionality volition hold out 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 y'all </data>} - Filtering By keyword: Wrong Message{type=TEXT, size=400, content=Wrong Message, should hold out filtered} - Filtering By maxSize: 200 Message{type=TEXT, size=300, content=Does Strategy pattern follows OCP blueprint principle?}
You tin forcefulness out run across that our List contains iv messages i of type XML in addition to 3 of type TEXT. So when nosotros commencement filter messages past times type XML, y'all tin forcefulness out run across 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 forcefulness out exercise unlike things from same code past times only providing a novel implementation of Strategy interface, this is the ability of Strategy blueprint pattern.
You tin forcefulness out besides usage lambda expressions to implement Strategy pattern inwards Java, equally y'all tin forcefulness out usage lambdas inwards house of anonymous class inwards 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 flat to stand upward for 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 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 total 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 closed to 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 inwards 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 inwards this real life instance of Strategy blueprint pattern inwards Java. As I said, since Strategy pattern confirms opened upward closed blueprint principle, y'all tin forcefulness out besides persuasion this equally an instance of Open Closed blueprint regulation inwards Java. Design patterns are tried in addition to tested way of solving employment inwards a item context in addition to noesis of total patterns actually helps y'all to write meliorate 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 larn to a greater extent than nigh blueprint pattern in addition to their effective usage inwards Java.
Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass
Belum ada Komentar untuk "Strategy Pattern Pattern In Addition To Opened Upwards Unopen Regulation Inwards Coffee - Example"
Posting Komentar