FactoryPattern
FactoryPattern
The factory design pattern is used when we have a superclass with multiple
sub-classes and based on input, we need to return one of the sub-class. This
pattern takes out the responsibility of the instantiation of a class from the client
program to the factory class.
Let’s first learn how to implement a factory design pattern in java and then we
will look into factory pattern advantages. We will see some of the factory
design pattern usage in JDK. Note that this pattern is also known as Factory
Method Design Pattern.
Let’s say we have two sub-classes PC and Server with below implementation.
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}
Notice that both the classes are extending Computer super class.
public class Server extends Computer {
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
Factory Class
Now that we have super classes and sub-classes ready, we can write our
factory class. Here is the basic implementation.
import com.journaldev.design.model.Computer;
import com.journaldev.design.model.PC;
import com.journaldev.design.model.Server;
return null;
}
}
Some important points about Factory Design Pattern method are;
1. We can keep Factory class Singleton or we can keep the method that returns
the subclass as static.
2. Notice that based on the input parameter, different subclass is created and
returned. getComputer is the factory method.
Here is a simple test client program that uses above factory design pattern
implementation.
import com.journaldev.design.factory.ComputerFactory;
import com.journaldev.design.model.Computer;
1. Factory design pattern provides approach to code for interface rather than
implementation.
2. Factory pattern removes the instantiation of actual implementation classes
from client code. Factory pattern makes our code more robust, less coupled
and easy to extend. For example, we can easily change PC class
implementation because client program is unaware of this.
3. Factory pattern provides abstraction between implementation and client
classes through inheritance.