What Is Mill Method Pattern Pattern Inward Coffee Amongst Illustration - Tutorial

Factory pattern pattern inwards Java i of the meat pattern pattern which is used heavily non solely inwards JDK but likewise inwards diverse Open Source framework such every bit Spring, Struts together with Apache along alongside decorator pattern pattern inwards Java. Factory Design pattern is based on Encapsulation object oriented concept. Factory method is used to create dissimilar object from manufactory often refereed every bit Item together with it encapsulate the creation code. So instead of having object creation code on customer side nosotros encapsulate within Factory method inwards Java. One of the best examples of manufactory pattern inwards Java is BorderFactory Class of Swing API. In this Design pattern tutorial nosotros volition encounter What is Factory method pattern pattern inwards Java, What are principal advantages of manufactory pattern inwards Java , Code instance of Factory pattern pattern together with What occupation Factory pattern solves inwards Java or when to purpose Factory pattern pattern.  This article is inwards continuation of my pattern pattern article every bit 10 OOPS together with SOLID pattern principles coffee programmer should know and How to purpose Observer pattern inwards Java

 

What is static manufactory method or manufactory pattern pattern

Class inwards Java together with it provides loose coupling together with high cohesion. Factory pattern encapsulate object creation logic which makes it slowly to modify it afterward when you lot modify how object gets created or you lot tin forcefulness out fifty-fifty innovate novel object alongside only modify inwards i class. In GOF pattern listing Factory pattern is listed every bit Creation pattern pattern. Factory should move an interface together with clients get-go either creates manufactory or instruct manufactory which afterward used to create objects.



Example of static manufactory method inwards JDK

 Best Example of Factory method pattern pattern is valueOf() method which is at that topographic point inwards String together with wrapper classes similar Integer together with Boolean together with used for type conversion i.e. from converting String to Integer or String to double inwards java..

Some to a greater extent than examples of manufactory method pattern pattern from JDK is :

valueOf() method which returns object created past times manufactory equivalent to value of parameter passed.

getInstance() method which creates instance of Singleton class.

newInstance() method which is used to create together with render novel instance from manufactory method every fourth dimension called.

getType() together with newType() equivalent of getInstance() together with newInstance() manufactory method but used when manufactory method resides inwards split class.

Problem which is solved past times Factory method Pattern inwards Java

Whenever nosotros speak virtually object oriented language it volition based upon only about concept similar abstraction, polymorphism etc together with on that encapsulation and delegation are of import concept whatever pattern volition move called skilful if occupation are delegated to dissimilar object together with only about sort of encapsulation is there.

Some fourth dimension our application or framework volition non know that what sort of object it has to create at run-time it knows solely the interface or abstract degree together with every bit nosotros know nosotros tin forcefulness out non create object of interface or abstract degree together with thence principal occupation is frame run knows when it has to create but don’t know what kind of object.

Whenever nosotros create object using new() nosotros violate principle of programming for interface rather than implementation which eventually effect inwards inflexible code together with hard to modify inwards maintenance. By using Factory pattern pattern inwards Java nosotros instruct rid of this problem.

Another occupation nosotros tin forcefulness out expression upwards is degree needs to incorporate objects of other classes or degree hierarchies within it; this tin forcefulness out move really easily achieved past times only using the novel keyword together with the degree constructor. The occupation alongside this approach is that it is a really hard coded approach to create objects every bit this creates dependency betwixt the ii classes.

So factory pattern solve this occupation really easily past times model an interface for creating an object which at creation fourth dimension tin forcefulness out permit its subclasses create upwards one's hear which degree to instantiate, Factory Pattern promotes loose coupling past times eliminating the ask to bind application-specific classes into the code. The factory methods are typically implemented every bit virtual methods, together with thence this pattern is likewise referred to every bit the “Virtual Constructor”. These methods create the objects of the products or target classes.

When to purpose Factory pattern pattern inwards Java

  • Static Factory methods are mutual inwards frameworks where library code needs to create objects of types which may move sub classed past times applications using the framework.        
  • Some or all concrete products tin forcefulness out move created inwards multiple ways, or nosotros desire to instruct out opened upwards the pick that inwards the hereafter at that topographic point may move novel ways to create the concrete product.
  • Factory method is used when Products don't ask to know how they are created.
  • We  tin forcefulness out purpose manufactory pattern where nosotros accept to create an object of whatever i of sub-classes depending on the information provided

Code Example of Factory Design Pattern inwards Java:

Let’s encounter an instance of how manufactory pattern is implemented inwards Code.We accept requirement to create multiple currency e.g. INR, SGD, USD together with code should move extensible to adapt novel Currency every bit well. Here nosotros accept made Currency every bit interface together with all currency would move concrete implementation of Currency interface. Factory Class volition create Currency based upon province together with render concrete implementation which volition move stored inwards interface type. This makes code dynamic together with extensible.

Here is consummate code instance of Factory pattern inwards Java:

interface Currency {
       String getSymbol();
}
// Concrete Rupee Class code
class Rupee implements Currency {
       @Override
       public String getSymbol() {
              return "Rs";
       }
}

// Concrete SGD degree Code
class SGDDollar implements Currency {
       @Override
       public String getSymbol() {
              return "SGD";
       }
}

// Concrete USA Dollar code
class USDollar implements Currency {
       @Override
       public String getSymbol() {
              return "USD";
       }
}

// Factroy Class code
class CurrencyFactory {

       public static Currency createCurrency (String country) {
       if (country. equalsIgnoreCase ("India")){
              return new Rupee();
       }else if(country. equalsIgnoreCase ("Singapore")){
              return new SGDDollar();
       }else if(country. equalsIgnoreCase ("US")){
              return new USDollar();
        }
       throw new IllegalArgumentException("No such currency");
       }
}

// Factory customer code
public class Factory {
       public static void main(String args[]) {
              String province = args[0];
              Currency rupee = CurrencyFactory.createCurrency(country);
              System.out.println(rupee.getSymbol());
       }
}


Advantage of Factory method Pattern inwards Java:

Factory pattern inwards Java is heavily used everywhere including JDK, opened upwards root library together with other frameworks.In next are principal advantages of using Factory pattern inwards Java:

1) Factory method pattern pattern decouples the calling degree from the target class, which effect inwards less coupled together with highly cohesive code?
E.g.: JDBC is a skilful instance for this pattern; application code doesn't ask to know what database it volition move used with, together with thence it doesn't know what database-specific driver classes it should use. Instead, it uses manufactory methods to instruct Connections, Statements, together with other objects to run with. Which gives you lot flexibility to modify your back-end database without changing your DAO layer inwards instance you lot are using ANSI SQL features together with non coded on DBMS specific feature?

2) Factory pattern inwards Java enables the subclasses to supply extended version of an object, because creating an object within manufactory is to a greater extent than flexible than creating an object take away inwards the client. Since customer is working on interface flat whatever fourth dimension you lot tin forcefulness out heighten the implementation together with render from Factory.

3) Another do goodness of using Factory pattern pattern inwards Java is that it encourages consistency inwards Code since every fourth dimension object is created using Factory rather than using dissimilar constructor at dissimilar customer side.

4) Code written using Factory pattern pattern inwards Java is likewise easy to debug and troubleshoot because you lot accept a centralized method for object creation together with every customer is getting object from same place.


Some to a greater extent than advantages of manufactory method pattern pattern is:
1. Static manufactory method used inwards manufactory pattern pattern enforces purpose of Interface than implementation which itself a skilful practice. for example:

Map synchronizedMap = Collections.synchronizedMap(new HashMap());

2. Since static manufactory method accept render type every bit Interface, it allows you lot to supplant implementation alongside improve functioning version inwards newer release.
3. Another payoff of static manufactory method pattern is that they tin forcefulness out cache oftentimes used object together with eliminate duplicate object creation. Boolean.valueOf() method is skilful instance which caches truthful together with imitation boolean value.
4. Factory method pattern is likewise recommended past times Joshua Bloch inwards Effective Java.
5 Factory method pattern offers choice means of creating object.
6. Factory pattern tin forcefulness out likewise move used to enshroud information related to creation of object.

That’s all on Factory pattern patten inwards Java for now. This is i of the most used patterns inwards Java library together with dissimilar Java frameworks. Summary is effort to purpose Factory pattern whenever you lot encounter an chance to encapsulate object creation code together with encounter adventure of creating dissimilar object inwards close future.

Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass

Komentar

Postingan populer dari blog ini

Virtualbox - /Sbin/Mount.Vboxsf: Mounting Failed Amongst The Error: Protocol Fault [Solution]

Top Ten Jdbc Interview Questions Answers For Coffee Programmer

Fix Protocol As Well As Cause Messaging Interview Questions