Strategy Blueprint Pattern As Well As Opened Upwards 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 inwards the champaign of object-oriented analysis as well as blueprint along amongst Decorator, Observer as well as Factory patterns. Strategy pattern allows you lot to encapsulate possible changes inwards a procedure as well as encapsulate that inwards a Strategy class. By doing that your procedure (mainly a method) depends upon a strategy, higher score 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 modify inwards a tested method. That's how it confirms open unopen blueprint principle.

Though similar whatever other blueprint pattern, it equally good introduces few to a greater extent than classes inwards your codebase, but that's worth doing because it meliorate organize your code as well as provides much-needed flexibility. It equally good makes it slow to modify attributes.

Strategy pattern is real useful, peculiarly for implementing algorithmic strategy e.g. encryption, compression, comparing etc. Influenza A virus subtype H5N1 duo of examples of Strategy pattern from JDK is Comparator as well as LayoutManager. You tin sentiment Comparator equally Strategy interface, define compare() method, forthwith 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 whatever modify 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 instance of Strategy pattern tin equally good survive seen equally an instance of open unopen blueprint principle, which states that a design, code (class or method) should stay opened upwards for extension but unopen for modification.

When nosotros say unopen for modification, it way novel changes should survive 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 equally good is ane of the behavioral pattern inwards GOF list, showtime introduced inwards classic GOF blueprint pattern book.

 Strategy blueprint pattern is based upon opened upwards unopen blueprint regulation Strategy Design Pattern as well as Open Closed Principle inwards Java - Example


In this example, we demand to filter the Incoming message past times for certain criterion e.g. filter message if it's of a detail type. But you lot know that this touchstone tin change, as well as you lot may demand to filter the message past times their size or a specific keyword inwards their content. In the pump of this operation, nosotros bring a filter() method inwards a cast say MessageUtils, this cast is responsible for filtering messages.

In the simplest form, but removing them from incoming List of Messages. In guild to proceed this code intact fifty-fifty when filtering strategy changes due to novel requirements, nosotros volition utilisation Strategy blueprint pattern.

In guild 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 3 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 equally good opened upwards for extension, equally 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, as well as insertion sort.

 Strategy blueprint pattern is based upon opened upwards unopen blueprint regulation Strategy Design Pattern as well as Open Closed Principle inwards Java - Example



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 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 examine 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 survive 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      * you lot tin render whatever filtering touchstone past times providing       * implementation of FilteringStrategy, but      * no demand to modify whatever code here.       * New functionality volition survive 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 survive filtered} - Filtering By maxSize: 200 Message{type=TEXT, size=300, content=Does Strategy pattern follows OCP blueprint principle?}

You tin run across that our List contains 4 messages ane of type XML as well as 3 of type TEXT. So when nosotros showtime filter messages past times type  XML, you lot tin 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 practise unlike things from same code past times but providing a novel implementation of Strategy interface, this is the ability of Strategy blueprint pattern.

You tin equally good utilisation lambda expressions to implement Strategy pattern inwards Java, equally you lot tin utilisation lambdas inwards house of anonymous class inwards 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
/* * Influenza A virus subtype H5N1 cast 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 cast is used to define unlike message types

MessageType.java
/* * Enum to announce unlike 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 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 upwards unopen blueprint principle, you lot tin equally good sentiment this equally an instance of Open Closed blueprint regulation inwards Java. Design patterns are tried as well as tested way of solving work inwards a detail context as well as noesis of marrow patterns actually helps you lot 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 nigh blueprint pattern as well as their effective utilisation inwards Java.

Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass



Sumber https://javarevisited.blogspot.com/

0 Response to "Strategy Blueprint Pattern As Well As Opened Upwards Unopen Regulation Inward Coffee - Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel