Strategy Blueprint Pattern Inward Coffee Using Enum - Tutorial Example

I guide maintain said this before that Java Enum is rattling versatile in addition to tin create lot to a greater extent than than y'all commonly human face from it. We guide maintain seen lot of examples of Enum inwards my before posts e.g. writing thread-safe Singleton using Enum in addition to 10 ways to work Enum inwards Java. In this article, nosotros volition  learn a novel way to work Enum, for implementing Strategy pattern pattern. Strategy pattern is 1 of the famous pattern, which takes wages of polymorphism, to take switch cases in addition to strive for opened upward unopen pattern principle. Formally it encapsulate related algorithm, known equally strategy in addition to brand them interchangeable. So your Client, likewise known equally Context, tin work dissimilar algorithm or strategy, without whatever modification. One of the fundamental wages of Strategy pattern is it's extensibility, i.e. introducing novel Strategy is equally slowly equally writing a novel course of report in addition to implementing Strategy interface, amongst Enum, instead of creating carve upward class, y'all creates a carve upward Enum instance, which agency less discover of classes in addition to amount create goodness if Strategy pattern.



How to implement Strategy pattern using Enum inwards Java

In this tutorial, nosotros volition encounter an instance of implementing Strategy pattern using Java Enum, I would work a sporting example. If y'all are cricket fan, similar me, y'all are going to connect amongst this article, but  if y'all are a Soccer or Tennis fan, than allow me explicate a fleck virtually example.

In Cricket, at that topographic point are 3 pop formats T20 (20 over match), One day(50 over match) in addition to Test(5 days match). If a player, plays all 3 format, he needs to accommodate it's batting strategy to live on effective. For example, T20 is all virtually scoring quickly, land One hateful solar daytime international games laissez passer fleck of fourth dimension for setting in addition to hence scoring. In contrast of shorter version, Test jibe is all virtually grinding i.e. occupying fold in addition to making certain your opponent acquire tired, before scoring briskly.


In our Strategy pattern example, nosotros guide maintain work an Enum to define dissimilar batting strategy. We guide maintain defined a default play() method in addition to since, Enum tin override methods, nosotros are overriding it on every instances i.e. on T20, ONE_DAY in addition to TEST. Our context class, which is named equally Player likewise has a play() method, which delegates to play() method of configurable Strategy.


UML diagram of Strategy Design Pattern

Here is the UML diagram of Strategy pattern inwards Java, Why y'all should depict UML diagram? because this is the best way to squall upward in addition to empathise how a pattern pattern works. In fact, this is the criterion ways to communicate your pattern to your swain developers in addition to squad members.

 I guide maintain said this before that Java Enum is rattling versatile in addition to tin create lot to a greater extent than than y'all nor Strategy Design Pattern inwards Java using Enum - Tutorial Example
In this diagram, I guide maintain explained strategy pattern pattern using sorting algorithm e.g. Bubble Sort, QuickSort, Insertion Sort  in addition to Selection Sort. For our code example, y'all tin supersede Strategy interface amongst Match, in addition to sorting strategy to T20, OneDay in addition to Test Matches.


Strategy Pattern Example using Enum

Here is amount code instance of implementing Strategy pattern pattern using Enum inwards Java. If y'all are coding inwards Eclipse IDE hence y'all don't postulate to create much, only select in addition to re-create this code, select the Java projection y'all are working inwards Eclipse IDE in addition to glue it. Eclipse volition accept assist of creating correct packages in addition to origin file amongst proper refer e.g. refer of populace class. This is the quickest way to travail in addition to execute Java code snippet from meshing inwards your IDE. Also remember, Strategy pattern is a skillful instance of Open Closed Design Principle of SOLID object oriented pattern principle.

import org.slf4j.Logger; import org.slf4j.LoggerFactory;  /**  * Java programme to demonstrate that Enum tin live on used to implement Strategy  * Pattern inwards Java.  *  * @author Javin  */ public class Match {      private static final Logger logger = LoggerFactory.getLogger(Match.class);      public static void main(String args[]) {                 Player ctx = new Player(Strategy.T20);         ctx.play();                 ctx.setStrategy(Strategy.ONE_DAY);         ctx.play();                 ctx.setStrategy(Strategy.TEST);         ctx.play();         }     }  /*  * Player class, which uses dissimilar Strategy implementation.  */ class Player{     private Strategy battingStrategy;         public Player(Strategy battingStrategy){         this.battingStrategy = battingStrategy;     }         public void setStrategy(Strategy newStrategy){         this.battingStrategy = newStrategy;     }         public void play(){         battingStrategy.play();     } }  /*  * An Enum to implement Strategy pattern pattern inwards Java. Different instances of  * Enum stand upward for dissimilar batting strategy, based upon type of game e.g. T20,  * One hateful solar daytime international or Test match.  */ enum Strategy {      /* Make certain to grade chop-chop on T20 games */     T20 {          @Override         public void play() {             System.out.printf("In %s, If it's inwards the V, brand certain it goes to tree %n", name());         }     },         /* Make a residuum betwixt attach in addition to defense inwards One hateful solar daytime */     ONE_DAY {          @Override         public void play() {             System.out.printf("In %s, Push it for Single %n", name());         }     },         /* Test jibe is all virtually occupying the fold in addition to grinding opposition */     TEST {          @Override         public void play() {             System.out.printf("In %s, Grind them difficult %n", name());         }     };      public void play() {         System.out.printf("In Cricket, Play equally per Merit of Ball %n");     } }  Output: In T20, If it's inwards the V, brand certain it goes to tree In ONE_DAY, Push it for Single In TEST, Grind them hard


That's all on How to implement Strategy pattern pattern inwards Java using Enum. You tin encounter that it's lot easier to implement Strategy pattern amongst Enum, y'all non alone reduced discover of classes, but likewise achieves extensibility in addition to flexibility of Strategy pattern. On downwards side, Yes, y'all postulate to alter your tried in addition to tested Enum every time, though past times inserting alone novel code, it's however violate Open Closed regulation a bit, which advocates that novel functionality should live on added past times writing novel code, rather than modifying existing code.

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 Inward Coffee Using Enum - Tutorial Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel