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.
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.
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.
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.
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.
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.
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:
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.
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.
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.
- 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.