Thursday, April 25, 2024
HomeJavaTechnique Design Sample in Java utilizing Enum

Technique Design Sample in Java utilizing Enum


Hiya guys, how are you doing? I hope you all are advantageous and doing good in your life and profession. At the moment, I’m going to speak concerning the Technique sample, one of many helpful design and coding sample which can enable you to to jot down versatile code. The code which might stand up to the take a look at of time in Manufacturing. I will additionally train you ways you should use Enum to implement the Technique design sample and Open Closed design precept higher in Java. I’ve stated this earlier than that Java Enum may be very versatile and might do much more than you usually anticipate from it. We’ve seen numerous examples of Enum in my earlier posts like writing thread-safe Singleton utilizing Enum and 10 methods to make use of Enum in Java.

On this article, we are going to study a brand new means to make use of Enum, for implementing the Technique design sample. Technique sample is likely one of the well-known sample, which takes benefit of polymorphism, to take away swap instances and try for the
open-closed design precept.

Formally it encapsulates associated algorithm, often called technique and make them interchangeable. So your Consumer, also called Context, can use a distinct algorithm or technique, with none modification.

One of many key benefits of Technique sample is it is extensibility, like introducing a brand new Technique is as simple as writing a brand new class and implementing Technique interface, with Enum, as a substitute of making a separate class, you create a separate Enum occasion, which implies much less variety of lessons and full profit if Technique sample.

Btw, in case you are new into the world of design sample then I recommend you study extra of them. They not solely enable you to to unravel frequent coding issues but in addition lets you write higher and versatile code. In order for you some assist in studying them, Java Design Patterns – The Full Masterclass can be utilized as a companion. It is one of many higher programs on Udemy on this subject.

UML diagram of the Technique Design Sample

Right here is the UML diagram of the Technique sample in Java, Why it is best to draw the UML diagram? as a result of that is the easiest way to recollect and perceive how a design sample works. In actual fact, that is the usual solution to talk your design to your fellow builders and staff members.

On this diagram, I’ve defined the technique design sample utilizing sorting algorithms like Bubble TypeQuickSortInsertion Type, and Merge Type. For our code instance, you’ll be able to substitute Technique interface with Match, and sorting technique to T20, OneDay, and Check Matches.

The UML diagram clearly highlights the connection between lessons and the Technique interface. You possibly can see the Technique interface has many implementations and they’re swapped on Context class relying upon which type of sorting you want.

You possibly can additional see  Java Design Patterns – The Full Masterclass course on Udemy to study extra concerning the Technique design sample in Java and likewise for contemporary implementation of basic object-oriented patterns.

Methods to implement a Technique sample utilizing Enum in Java

On this tutorial, we are going to see an instance of implementing a Technique sample utilizing Java Enum, I’d use a sporting instance. If you’re a cricket fan, like me, you’re going to join with this text, however in case you are a Soccer or Tennis fan than let me clarify a bit concerning the instance.

In Cricket, there are three in style codecs T20 (20 over match), In the future(50 over match), and Check(5 days match). If a participant, performs all three codecs, he wants to regulate its batting technique to be efficient.

For instance, T20 is all about scoring shortly, whereas One-day worldwide video games give a little bit of time for setting after which scoring. In distinction to the shorter model, the Check match is all about grinding i.e. occupying the crease and ensuring your opponent will get drained, earlier than scoring briskly.

In our Technique sample instance, now we have used an Enum to outline completely different batting technique. We’ve outlined a default play() technique and since Enum can override strategies, we’re overriding it on each occasion like on T20, ONE_DAY, and TEST.

Our context class, which is known as as Participant additionally has a play() technique, which delegates to play() technique of configurable Technique.  Btw, in case you are not conversant in Enum in Java and it is important options like overriding strategies, I recommend you be part of The Full Java Masterclass course on Udemy. It is one of the up-to-date programs to study Java and lately up to date to cowl the most recent Java model as effectively.

Strategy Design Pattern in Java using Enum - Tutorial Example

Technique Sample Instance utilizing Enum

Here’s a full code instance of implementing a Technique design sample utilizing Enum in Java. If you’re coding in Eclipse IDE then you definately needn’t do a lot, simply choose and replica this code, choose the Java mission you might be working in Eclipse IDE and paste it.

Eclipse IDE will care for creating the suitable packages and supply information with a correct title just like the title of a pa public class.

That is the quickest solution to try to execute Java code snippets from the web in your IDE. Additionally bear in mind, the Technique sample is an effective instance of the Open Closed Design Precept of SOLID object-oriented design ideas coined by Uncle Bob in his basic Clear Codebook.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Java program to show that Enum can be utilized to implement Technique
 * Sample in Java.
 *
 * @creator Javin
 */
public class Match {

    non-public static ultimate Logger logger = LoggerFactory.getLogger(Match.class);

    public static void most important(String args[]) {
       
        Participant ctx = new Participant(Technique.T20);
        ctx.play();
       
        ctx.setStrategy(Technique.ONE_DAY);
        ctx.play();
       
        ctx.setStrategy(Technique.TEST);
        ctx.play();
   
    }

  
}

/*
 * Participant class, which makes use of completely different Technique implementation.
 */
class Participant{
    non-public Technique battingStrategy;
   
    public Participant(Technique battingStrategy){
        this.battingStrategy = battingStrategy;
    }
   
    public void setStrategy(Technique newStrategy){
        this.battingStrategy = newStrategy;
    }
   
    public void play(){
        battingStrategy.play();
    }
}

/*
 * An Enum to implement Technique design sample in Java. Totally different cases of
 * Enum characterize completely different batting technique, primarily based upon kind of recreation e.g. T20,
 * In the future worldwide or Check match.
 */
enum Technique {

    /* Be certain that to attain shortly on T20 video games */
    T20 {

        @Override
        public void play() {
            System.out.printf("In %s, If it is within the V, be sure it goes to tree %n",
                             title());
        }
    },
   
    /* Make a stability between connect and defence in In the future */
    ONE_DAY {

        @Override
        public void play() {
            System.out.printf("In %s, Push it for Single %n", title());
        }
    },
   
    /* Check match is all about occupying the crease and grinding opposition */
    TEST {

        @Override
        public void play() {
            System.out.printf("In %s, Grind them onerous %n", title());
        }
    };

    public void play() {
        System.out.printf("In Cricket, Play as per Advantage of Ball %n");
    }
}

Output:
In T20, If it's within the V, be sure it goes to tree
In ONE_DAY, Push it for Single
In TEST, Grind them onerous

That is all on Methods to Implement the Technique design sample in Java utilizing Enum. You possibly can see that it is loads simpler to implement Technique sample with Enum, you not solely lowered the variety of lessons but in addition achieves extensibility and suppleness of Technique sample. On the draw back, Sure, you must change your tried and examined Enum each time, although by inserting solely new code, it nonetheless violates Open Closed precept a bit, which advocates that new performance needs to be added by writing new code, fairly than modifying present code.

Additional Studying
Design Sample Library
From 0 to 1: Design Patterns – 24 That Matter – In Java
Java Design Patterns – The Full Masterclass

If you happen to like this text and thinking about studying extra about design patterns and ideas, chances are you’ll like following ones as effectively :

  • 5 Free Programs to study Object Oriented Programming (programs)
  • 10 Object-Oriented Design Precept Each Programmer Ought to know (ideas)
  • Methods to implement the Builder design sample in Java? (answer)
  • 5 Causes to make use of Composition rather than Inheritance in Java? (reply)
  • What’s the Open-Closed design Precept in OOP? (reply)
  • What’s the distinction between Manufacturing unit and Summary Manufacturing unit Design Patterns? (reply)
  • What’s the distinction between State and Technique patterns in Java? (reply)
  • Methods to implement the Technique Design Sample utilizing Java Enum? (answer)
  • Why implementing Singleton utilizing Enum is healthier than Class in Java? (reply)
  • Prime 5 Books to Be taught Design Patterns and Ideas (books)
  • Methods to implement DAO design Sample in Java? (reply)
  • What’s the distinction between Affiliation, Aggregation, and Composition in OOP? (reply)
  • What’s the distinction between Singleton and Static Class in Java? (reply)
  • Why must you Interface for Coding in Java? (reply)
  • An actual-life instance of the Decorator Sample in Java? (instance)
  • What’s the distinction between Adapter, Decorator, and Proxy design patterns? (reply)
  • 5 On-line Programs to study Design Sample in Java (programs)

Thanks for studying this text up to now. If you happen to like this text concerning the Manufacturing unit design sample and Dependency Injection sample in Java then please share it with your folks and colleagues. In case you have any questions or suggestions then please drop a be aware.

P. S. – If you’re in search of some free course to start out studying design patterns, there’s a good one on Udemy referred to as Java Design Patterns and Structure by John Purcell. It would not cowl all of the GOF patterns however nonetheless, it is good to study all of the necessary ones and architectures like MVC.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments