Home Education and learning Web hosting and design Small Business
Factory design Patterns design Patterns
Factory pattern abstracts the creation and initialization of the object.
The Factory patterns can be used in following cases:
1. Use this design pttern when a class does not know which class of objects it must create.
2. If one of the sub-class needs to be Instantiated based upon some input parameter then this type of design pattern can be used.
Class diagram
Sample Code:




/** File name: DbComponentFactory.java **/


package factorypattern;

public class DbComponentFactory {

    public static AbstractDbComponent createDbComponent(String dbcomponentname) {
        
        if (dbcomponentname == "ORACLE")  {
            return new OracleDbComponent();
        }
        else if (dbcomponentname == "MYSQL")  {
            return new MysqlDbComponent();
        }
        return null ;
    }
 
}






/** File name: OracleDbComponent.java **/

package factorypattern;

public abstract class AbstractDbComponent {
    public abstract void execute();


}






/** File name: OracleDbComponent.java **/

package factorypattern;

public class OracleDbComponent extends AbstractDbComponent {

    public OracleDbComponent() {
        System.out.println("Creating ORACLE DB Component");
    }
    
    public void execute() {
        System.out.println("ORACLE: Executing using OracleDbComponent") ;
    }
}





/** File name: MysqlDbComponent.java **/

package factorypattern;

public class MysqlDbComponent extends AbstractDbComponent {
    public MysqlDbComponent() {
        System.out.println("Creating MYSQL DB Component");
    }
    
    public void execute() {
        System.out.println("MYSQL:  Executing using MysqlDbComponent") ;
    }
}






/** File name: Main.java **/

package factorypattern;

public class Main {
    
    /** Creates a new instance of Main */
    public Main() {
        System.out.println("TEST for oracle component: ");
        AbstractDbComponent dbcomponent = 
                  DbComponentFactory.createDbComponent("ORACLE");
        dbcomponent.execute();
        
        
        System.out.println("\n\n\nTEST for Mysql component: ");
        dbcomponent = DbComponentFactory.createDbComponent("MYSQL");
        dbcomponent.execute();
        
    }

    public static void main(String[] args) {
        new Main();
    }
    
}







Following output is generated:

TEST for oracle component: Creating ORACLE DB Component ORACLE: Executing using OracleDbComponent

TEST for Mysql component: Creating MYSQL DB Component MYSQL: Executing using MysqlDbComponent BUILD SUCCESSFUL (total time: 0 seconds)

teacherone provides material for training only. We do not warrant the correctness of its contents. The risk from using it lies entirely with the user. teacherone is not liable for any damage or loss.