Strategy Pattern Pattern Inward Coffee Using Enum - Tutorial Example
I direct keep said this before that Java Enum is rattling versatile in addition to tin flame create lot to a greater extent than than you lot usually await from it. We direct keep 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 ane 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, besides known equally Context, tin flame work dissimilar algorithm or strategy, without whatever modification. One of the primal wages of Strategy pattern is it's extensibility, i.e. introducing novel Strategy is equally tardily equally writing a novel course of written report in addition to implementing Strategy interface, amongst Enum, instead of creating split upward class, you lot creates a split upward Enum instance, which way less let on of classes in addition to amount create goodness if Strategy pattern.
In Cricket, in that place are iii pop formats T20 (20 over match), One day(50 over match) in addition to Test(5 days match). If a player, plays all iii format, he needs to suit it's batting strategy to live on effective. For example, T20 is all nearly scoring quickly, piece One solar daytime international games plow over fleck of fourth dimension for setting in addition to and then scoring. In contrast of shorter version, Test gibe is all nearly grinding i.e. occupying plication in addition to making certain your opponent acquire tired, before scoring briskly.
In our Strategy pattern example, nosotros direct keep work an Enum to define dissimilar batting strategy. We direct keep defined a default play() method in addition to since, Enum tin flame 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 besides has a play() method, which delegates to play() method of configurable Strategy.
In this diagram, I direct keep explained strategy pattern pattern using sorting algorithm e.g. Bubble Sort, QuickSort, Insertion Sort in addition to Selection Sort. For our code example, you lot tin flame supersede Strategy interface amongst Match, in addition to sorting strategy to T20, OneDay in addition to Test Matches.
That's all on How to implement Strategy pattern pattern inwards Java using Enum. You tin flame run into that it's lot easier to implement Strategy pattern amongst Enum, you lot non exclusively reduced let on of classes, but besides achieves extensibility in addition to flexibility of Strategy pattern. On downwards side, Yes, you lot demand to alter your tried in addition to tested Enum every time, though past times inserting exclusively novel code, it's nevertheless 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
How to implement Strategy pattern using Enum inwards Java
In this tutorial, nosotros volition run into an instance of implementing Strategy pattern using Java Enum, I would work a sporting example. If you lot are cricket fan, similar me, you lot are going to connect amongst this article, but if you lot are a Soccer or Tennis fan, than allow me explicate a fleck nearly example.In Cricket, in that place are iii pop formats T20 (20 over match), One day(50 over match) in addition to Test(5 days match). If a player, plays all iii format, he needs to suit it's batting strategy to live on effective. For example, T20 is all nearly scoring quickly, piece One solar daytime international games plow over fleck of fourth dimension for setting in addition to and then scoring. In contrast of shorter version, Test gibe is all nearly grinding i.e. occupying plication in addition to making certain your opponent acquire tired, before scoring briskly.
In our Strategy pattern example, nosotros direct keep work an Enum to define dissimilar batting strategy. We direct keep defined a default play() method in addition to since, Enum tin flame 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 besides 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 you lot should depict UML diagram? because this is the best way to think in addition to sympathize how a pattern pattern works. In fact, this is the touchstone ways to communicate your pattern to your beau developers in addition to squad members.In this diagram, I direct keep explained strategy pattern pattern using sorting algorithm e.g. Bubble Sort, QuickSort, Insertion Sort in addition to Selection Sort. For our code example, you lot tin flame 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 you lot are coding inwards Eclipse IDE in addition to then you lot don't demand to create much, simply select in addition to re-create this code, select the Java projection you lot are working inwards Eclipse IDE in addition to glue it. Eclipse volition direct keep assist of creating correct packages in addition to origin file amongst proper mention e.g. mention of populace class. This is the quickest way to endeavor in addition to execute Java code snippet from cyberspace inwards your IDE. Also remember, Strategy pattern is a proficient instance of Open Closed Design Principle of SOLID object oriented pattern principle.import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Java plan to demonstrate that Enum tin flame 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 correspond dissimilar batting strategy, based upon type of game e.g. T20, * One solar daytime international or Test match. */ enum Strategy { /* Make certain to marking speedily 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 residual betwixt attach in addition to defense strength inwards One solar daytime */ ONE_DAY { @Override public void play() { System.out.printf("In %s, Push it for Single %n", name()); } }, /* Test gibe is all nearly occupying the plication 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 flame run into that it's lot easier to implement Strategy pattern amongst Enum, you lot non exclusively reduced let on of classes, but besides achieves extensibility in addition to flexibility of Strategy pattern. On downwards side, Yes, you lot demand to alter your tried in addition to tested Enum every time, though past times inserting exclusively novel code, it's nevertheless 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
Komentar
Posting Komentar