In Factory pattern, we create an object without exposing the creation logic to the client and refer to newly created object using a common interface.
For example, Toy Factory
interface class Toy {
void make();
}
The concrete classes
Class Car implements Toy {
@Override
public void make() {
}
}
Class Helicopter implements Toy {
@Override
public void make() {
}
}
Class ToyFactory {
public Toy createToy(String toyName) {
if(toyName == "Car") {
return new Car();
}
else if(toyName == "Helicopter") {
return new Helicopter();
}
}
}
For example, Toy Factory
interface class Toy {
void make();
}
The concrete classes
Car
and Helicopter
inherit from super class Toy
. They're pretty straightforward.Class Car implements Toy {
@Override
public void make() {
}
}
Class Helicopter implements Toy {
@Override
public void make() {
}
}
Class ToyFactory {
public Toy createToy(String toyName) {
if(toyName == "Car") {
return new Car();
}
else if(toyName == "Helicopter") {
return new Helicopter();
}
}
}