Sabtu, 25 Februari 2017

Factory Method Pattern

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.

Advantage of Factory Design Pattern

  • Factory Method Pattern allows the sub-classes to choose the type of objects to create.
  • It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. 


Use of Factory Design Pattern

  • When a class doesn't know what sub-classes will be required to create
  • When a class wants that its sub-classes specify the objects to be created.
Let's see with the help of an example. Let's create a MobileFactory class that will return an instance of MobileType(Android, IOS, Windows) object.

package com.rn;

public abstract class MobileType {

public abstract String mobileType();
}
package com.rn;

public enum Mobile {
ANDROID, IOS,WINDOWS;
}
package com.rn;

public class Android extends MobileType {

@Override
public String mobileType() {
return "Gretting from Android, Mobile request taken and in process..";

}

}
    
package com.rn;

public class IOS extends MobileType {

@Override
public String mobileType() {
return "Gretting from IOS, Mobile request taken and in process..";
}

}

       
package com.rn;

public class Windows extends MobileType {

@Override
public String mobileType() {
return "Gretting from Windows, Mobile request taken and in process..";
}

}
       
package com.rn;

public class MobileFactory {

public MobileType prepareMobile(String mobile){
if(mobile.equals(Mobile.ANDROID.toString())){
return new Android();
}else if(mobile.equals(Mobile.IOS.toString())){
return new IOS();
}else if(mobile.equals(Mobile.WINDOWS.toString())){
return new Windows();
}
return null;
}
}
       
package com.rn;

public class ManufactureMobile {

public static void main(String args[]){

MobileFactory mobileFactory = new MobileFactory();
MobileType mobile = mobileFactory.prepareMobile(Mobile.ANDROID.toString());
System.out.println(mobile.mobileType());

mobile = mobileFactory.prepareMobile(Mobile.IOS.toString());
System.out.println(mobile.mobileType());

mobile = mobileFactory.prepareMobile(Mobile.WINDOWS.toString());
System.out.println(mobile.mobileType());
}
}

Run the ManufactureMobile.java and see the output:




Download the project from here

Tidak ada komentar:

Posting Komentar