Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to implement Factory Design Pattern in Java ?.

Program to demonstrate how to implement Factory Design Pattern in Java.

1. Animal.java 

package com.hubberspot.designpattern.creational.factorymethod;

// 1. Create a Animal interface
// having a method definition say eat
public interface Animal {

    public void eat();

}


2. AnimalFactory.java 

package com.hubberspot.designpattern.creational.factorymethod;

// 2. Create a AnimalFactory which 
// will create instances of concrete
// Animals
public class AnimalFactory {

    // 3. Create a static getAnimal method which will
    // take package name + class name of class whose
    // instance is to be created.
    public static Animal getAnimal(String classInfo) {
        Animal animal = null;
        try {
            // 4. Class.forName(String) dynamically loads class
            // passed as a String to it. 
            // 5. newInstance() method creates a concrete instance of
            // the class passed to Class.forName() as a String.
            animal = (Animal) Class.forName(classInfo).newInstance();
        } catch (Exception e) {           
            e.printStackTrace();
        } 
        // 6. We return the concrete instance.
        return animal;
    }

}


3. Dog.java 

package com.hubberspot.designpattern.creational.factorymethod;

// 8. Concrete animal Dog for the Animal interface
public class Dog implements Animal {

    @Override
    public void eat() {

        System.out.println("Dog eating .... ");

    }

}


4. Cat.java 

package com.hubberspot.designpattern.creational.factorymethod;

// 7. Concrete animal Cat for the Animal interface
public class Cat implements Animal {

    @Override
    public void eat() {

        System.out.println("Cat eating .... ");

    }

}


5. TestFactoryDesignPattern.java 

package com.hubberspot.designpattern.creational.factorymethod;

import com.hubberspot.designpattern.creational.factorymethod.Dog;

public class TestFactoryDesignPattern {

    public static void main(String[] args) {

        // 9. Create a Dog object from the AnimalFactory by passing fully
        // qualified name for the concrete Dog class
        Dog dog = (Dog) AnimalFactory.getAnimal(
                "com.hubberspot.designpattern.creational.factorymethod.Dog"
                );
        dog.eat();

        // 10. Create a Cat object from the AnimalFactory by passing fully
        // qualified name for the concrete Cat class
        Cat cat = (Cat) AnimalFactory.getAnimal(
                "com.hubberspot.designpattern.creational.factorymethod.Cat"
                );
        cat.eat();

    }


}


Output of the program : 


 




Video tutorial to demonstrate how to implement Factory Design Pattern in Java.















 
© 2021 Learn Java by Examples Template by Hubberspot