Sunday, May 12, 2024
HomeJavaHow one can implement Technique Design Sample in Java? (with Actual World...

How one can implement Technique Design Sample in Java? (with Actual World Instance, Professionals and Cons)


Technique Design sample is one among most helpful versatile sample, you’ll typically see utilized in Object Oriented design. This sample is likely one of the behavioral sample talked about by well-known Gang of 4 in there design sample classics Parts of Reusable Design Sample is Software program growth. As per definition goes, Technique sample permits you to encapsulate a set of algorithms and make them interchangeable. One of the best factor about Technique sample is that it permits you to cross a dynamic code to a way very like Lambda expression. The truth is, it was one of many strategy to obtain similar impact previous to Java 8. Additionally, there are a number of instance of Technique Sample in JDK itself like Comparator and Comparable are the perfect instance of Technique Sample in Java. 

Technique Sample in Java – A Actual world Instance

Take a look at under code for calculating postal costs, primarily based upon weight and supply kind of Merchandise to be posted. On floor this code seems to be good nevertheless it has a critical upkeep downside. A component which may be very a lot prone to change i.e. supply kind is just not correctly encapsulated. This code violets Open Closed design precept, as a result of it is not closed for modification.

In future if you could add one other supply kind say AIRMAIL, you then not solely have to switch DeliveryType, but in addition PostageCalculator which isn’t apparent. This will introduce bug on a tried and examined manufacturing system. 

Through the use of Technique design sample, we will remedy this upkeep downside and make this code Open for extension and Closed for modification. We’ll introduce a PostageCalculationStrategy to calculate postage for various sorts of supply medium.
import org.apache.log4j.Logger;

/**
  * Java program to implement Technique design sample. This design violets
  * Open closed design precept, and never closed for modification. Through the use of
  * Technique sample, we are going to repair this hole.

  * @writer Javin
  */
public class StrategyPatternDemo {

    non-public static closing Logger logger = Logger.getLogger(Take a look at.class);

    public static void important(String args[]) {
        Merchandise present = new Merchandise(100);
        int postalCharge = PostageCalculator.postage(present, DeliveryType.REGISTERED);

        System.out.printf("Weight : %dg, Supply Sort : %s, 
Postal Expenses : %dc %n",
                present.getWeight(), DeliveryType.REGISTERED, postalCharge );
     
        postalCharge = PostageCalculator.postage(present, DeliveryType.SPEEDPOST);
     
        System.out.printf("Weight : %dg, Supply Sort : %s,
 Postal Expenses : %dc %n",
                present.getWeight(), DeliveryType.SPEEDPOST, postalCharge );
    }
}

enum DeliveryType {
    SPEEDPOST, REGISTERED, SURFACE_MAIL;
}

class Merchandise {
    non-public int weight;  //in grams

    public Merchandise(int weight) {
        this.weight = weight;
    }

    public int getWeight() {
        return weight;
    }
}

class PostageCalculator {

    public static int postage(Merchandise merchandise, DeliveryType deliveryType) {    
        int postage = 0;

        change (deliveryType) {
            case SURFACE_MAIL:
                postage = merchandise.getWeight()  1; //1 cent per gram
                break;
            case REGISTERED:
                postage = merchandise.getWeight()  5; //5 cent per gram
                break;
            case SPEEDPOST:
                postage = merchandise.getWeight()  8; //8 cent per gram
                break;
            default:
                throw new IllegalArgumentException("Invalid Supply kind");
        }

        return postage;
    }
}
Output
Weight : 100g, Supply Sort : REGISTERED, Postal Expenses : 500c
Weight : 100g, Supply Sort : SPEEDPOST, Postal Expenses : 800c

Technique design sample Implementation to repair Open closed violation :

import org.apache.log4j.Logger;

/**
  * Java program to implement Technique design sample. This design voilates
  * Open closed design precept, and never closed for modification. Through the use of
  * Technique sample, we are going to repair this hole.
  *
  * @writer
  */
public class StrategyTest {

    non-public static closing Logger logger = Logger.getLogger(StrategyTest.class);

    public static void important(String args[]) {
        Merchandise present = new Merchandise(100);
        PostageCalculator postCalc = new PostageCalculator(new SurfaceMail());
     
        int postalCharge = postCalc.postage(present);

        System.out.printf("Weight : %dg, Supply Sort : %s, 
Postal Expenses : %dc %n",
                present.getWeight(), postCalc.getDeliveryType(), postalCharge );
     
        postCalc.setDeliveryType(new SpeedPost());
        postalCharge = postCalc.postage(present);
     
        System.out.printf("Weight : %dg, Supply Sort : %s, 
Postal Expenses : %dc %n",
                present.getWeight(), postCalc.getDeliveryType(), postalCharge );
    }
}

class Merchandise {
    non-public int weight;  //in grams

    public Merchandise(int weight) {
        this.weight = weight;
    }

    public int getWeight() {
        return weight;
    }
}

class PostageCalculator {
    non-public DeliveryType deliveryType;

    public DeliveryType getDeliveryType() {
        return deliveryType;
    }

    public void setDeliveryType(DeliveryType deliveryType) {
        this.deliveryType = deliveryType;
    }
 
    public PostageCalculator(DeliveryType medium){
        this.deliveryType = medium;
    }
 

    public int postage(Merchandise merchandise) {    
        return merchandise.getWeight()deliveryType.price();

    }
}

interface DeliveryType{
    public int price();
}

class SurfaceMail implements DeliveryType{

    @Override
    public int price() {
        return 1;
    }

}

class RegisteredMail implements DeliveryType{

    @Override
    public int price() {
       return 5;
    }
 
}

class SpeedPost implements DeliveryType{

    @Override
    public int price() {
        return 8;
    }

}

Now you’ll be able to see that, PostageCalculator’s postage() methodology is not going to be modified, when a brand new supply kind can be launched. That is the ability of open closed design precept, now code is closed for modification however open for extension in type of new DeliveryType implementation.

Professionals and Cons of Technique Design sample in Java

Listed here are couple of benefit and drawback of utilizing Technique Patter in Java or any Object Oriented Design.

1) One of many important benefit of Technique Sample is that it makes your software program Open for Extension however Closed for modification by making use of Open closed design precept. This implies, your tried and examined code stays unchanged, whenever you add new functionalities to your software program.

2) One other benefit of utilizing Technique design sample is that, the category which makes use of Technique in our instance PostageCalculator is loosely coupled with completely different Technique implementation e.g. Technique which calculate postal costs for various supply kind. All it is aware of is that, technique implementation implement a typical Technique interface to name the required methodology.

3) Technique Sample additionally promotes Single Accountability Principle. Shopper class, which calculates postal cost is now unbiased of price related to completely different supply varieties. Later for those who resolve to provided any low cost on a selected supply kind, or a price of a supply kind modifications. 

Your change will solely be restricted up-to a selected DeliveryType. Alternatively if you could do one thing, which is commons throughout all supply kind e.g. imposing a service cost, Solely this class must be modified, with out affecting how price for various Supply varieties are calculated.

4) Use of Technique Sample additionally makes testing simple. Since Shopper Code, which makes use of Methods are solely depending on a Technique interface and never on any specific implementation, you’ll be able to take a look at code inside Shopper, even when your technique or algorithm is just not prepared. 

You may create a mock object or dummy implementation on your Technique to check consumer code. instance of that is Collections.type() methodology, which does sorting. You may take a look at this code by offering a mock Comparator, which defines comparability technique.

5) Technique Sample vastly simplify consumer code, consumer like Sorting methodology can delegate comparability of object to Comparator in a single line. Like in our instance calculating price of various supply modicum is delegated.

6) One of many important benefit and distinction which you seen in code earlier than and after utilizing Technique sample is elimination of conditional statements like change and chain of if…else statements.

7) One other good thing about this sample which comes from use of Open closed design precept is extensibility, you might be free to implement as many algorithm or technique as you want. This extensibility is de facto large, simply think about what number of instances Comparator has been carried out for various kinds of object.

We’ve got seen lot of benefits and advantages of Technique sample in Java, now let’s check out among the drawback of utilizing this :

1) It will increase variety of courses in a system by encapsulating completely different algorithms.

2) Shopper should learn about completely different technique obtainable, to compose person class at runtime.

Additionally, right here is  UML diagram of Technique design sample to know the intent and construction of Technique Design Sample in Java:

Strategy Design Pattern in Java - Pros, Cons and Example

Issues to recollect about Technique Sample

Now, we now have seen what’s Technique design Sample, an actual life instance of Technique sample in Java and couple of execs and cons of utilizing Technique, it is excessive time to look again and revise couple of essential issues, which is value remembering.

1. Technique Sample permits a Shopper to make use of completely different algorithm, primarily based upon various kinds of calculation. For instance a SalaryCalcuator can use completely different technique to calculate wage primarily based upon kind of worker. E.g. utilizing hourly price for Hourly worker, day by day price for day by day worker and stuck month-to-month wage together with allowance for full time workers.

3. Since Shopper makes use of Composition to make use of Technique, i.e. it incorporates an occasion variable of Technique interface kind. Shopper consists with proper algorithm or technique at runtime, both utilizing constructor or setter injection.

4. Among the finest instance of Technique sample in JDK is Comparator interface, which defines an technique to check object. Since completely different object is in contrast in another way, Shopper which makes use of Comparator e.g. Collections.type(), which makes use of Comparator for sorting goal, is offered proper Technique at runtime. Benefit of that is that, code to type the gathering  is unbiased of kind of object and the way they evaluate. All it must know that, they implement Comparator and has evaluate() methodology.

That is all about what’s Technique sample in Java and how you can implement it. We’ve got seen an actual life instance of Technique design sample, which repair a design which violets open closed design precept. Technique is a really helpful sample in Object Oriented world and also you might need seen a variety of use circumstances for it. It additionally promotes use of Composition, which additional provides flexibility in design. Comparator class in Java can be a well-liked instance of Technique Sample, the place comparability technique is modified primarily based upon kind of object.

Different Java Design Patterns tutorials it’s possible you’ll like

  • How one can implement Template Design Sample in Java (Template Sample)
  • 5 Free Programs to be taught Object Oriented Programming (programs)
  • Distinction between Manufacturing facility and Dependency Injection Sample? (reply)
  • How one can design a Merchandising Machine in Java? (questions)
  • How one can implement a Decorator design sample in Java? (tutorial)
  • 18 Java Design Sample Interview Questions with Solutions (checklist)
  • When to make use of Command Design Sample in Java (instance)
  • 20 System Design Interview Questions (checklist)
  • 7 Greatest Programs to be taught Design Sample in Java (programs)
  • Distinction between State and Technique Design Sample in Java? (reply)
  • 7 Books to be taught System Design for Learners (System design books)
  • How one can create thread-safe Singleton in Java (instance)
  • Distinction between Manufacturing facility and Summary Manufacturing facility Sample? (instance)
  • 5 Free Programs to be taught Information Construction and Algorithms (programs)
  • How one can use Manufacturing facility methodology design sample in Java? (tutorial)
  • 7 Greatest Books to be taught the Design Sample in Java? (books)
  • How one can use Composite Design Sample in Java (composite instance)

Thanks loads for studying this text thus far. In case you like this instance
and tutorial of Technique Design Sample in Java then please share it
with your mates and colleagues. You probably have any
questions or suggestions then please drop a word.

P. S. – In case you are an skilled Java developer and  searching for a greatest design sample assets like
books and on-line programs then you too can checkout this checklist of greatest design sample programs for expertise builders to start out with. It incorporates nice on-line programs to be taught design sample and how you can use them in actual world coding. 



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments