Factory
- Java course
- Advanced
- Lesson 38/82
- 5 min
Learn the Factory pattern.
The Factory pattern
The Factory moves object creation to a central place. The client does not need to know which concrete class is created; it works only through an interface. This frees the code from depending on concrete classes.
Example: ShapeFactory.create("circle") returns a Shape; whether it is a Circle or another class does not concern the client. To add a new shape type you only change the factory method. This flexibility is especially valuable in large systems.
Interface and concrete classes
The foundation of a Factory is a common interface. The Shape interface declares a draw method; Circle and Square implement it. The factory returns the right concrete class based on a parameter.
So the client writes Shape s = factory.create("circle") and calls s.draw(); the concrete type stays hidden. Adding new concrete classes without changing the interface becomes easy, supporting the open-closed principle.
Practice Create a shape with ShapeFactory
Define a Shape interface with void draw(). A Circle class implements it and prints circle with System.out.println inside draw. In ShapeFactory, a static Shape create(String type) method returns new Circle() when type is "circle". In main, get a shape with ShapeFactory.create("circle") and call draw.
Starter code
// Define the Shape interface and Circle class
// Add the ShapeFactory.create method
// Call draw in mainSample solution
interface Shape { void draw(); }
class Circle implements Shape {
public void draw() { System.out.println("circle"); }
}
class ShapeFactory {
public static Shape create(String type) {
if (type.equals("circle")) return new Circle();
return null;
}
}
public class FactoryDemo {
public static void main(String[] args) {
Shape s = ShapeFactory.create("circle");
s.draw();
}
}Expected output
circle
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the Factory pattern hide?
- The data
- Which concrete class is created Correct answer
- The method signature
- The interface
Explanation: The Factory hides which concrete class is created from the client.
2 Match the Factory concepts
| Term | Meaning |
|---|---|
create("circle") |
Factory method |
Shape |
Common interface |
Circle |
Concrete class |
s.draw() |
Client call |
3 Complete the Factory call
Shape s = ShapeFactory.create(____);
Shape s = ShapeFactory.create("circle");
Explanation: The type parameter is given as a string.