Can you explain the Factory design pattern with a simple example in Java?
Aug 02, 2025 am 08:44 AMThe factory design pattern creates objects centrally through a factory class, avoiding the client using new hard code to instantiate specific classes; 2. Define the abstract product Pizza, and the specific products CheesePizza, VeggiePizza and PepperoniPizza inherit it; 3. PizzaFactory returns the corresponding Pizza instance according to the input type; 4. The client creates objects through the factory and calls its methods to achieve loose coupling and creation logic encapsulation, which is convenient for expansion and maintenance. This implementation is a simple factory pattern, ending with a complete sentence.
Sure! The Factory design pattern is a creative pattern that provides a way to create objects without specifying the exact class of object that will be created. It promotes loose coupling by letting subclasses decide which class to instantiate.

Let's understand it with a simple real-world example: creating different types of pizzas .
? Problem
You want to create a Pizza
object, but you don't want to hardcode whether it's a CheesePizza
, VeggiePizza
, or PepperoniPizza
every time. You want a centralized way to create them based on input.

? Solution: Factory Pattern
We'll define:
- A common interface or superclass (
Pizza
) - Concrete classes (
CheesePizza
,VeggiePizza
) - A
PizzaFactory
class that decides which pizza to create
Step-by-step Java Example
1. Define the Product (Pizza interface)
// Pizza.java abstract class Pizza { String name; void prepare() { System.out.println("Preparing " name); } void bake() { System.out.println("Baking " name); } void cut() { System.out.println("Cutting " name); } void box() { System.out.println("Boxing " name); } }
2. Create Concrete Products
// CheesePizza.java class CheesePizza extends Pizza { public CheesePizza() { name = "Cheese Pizza"; } } // VeggiePizza.java class VeggiePizza extends Pizza { public VeggiePizza() { name = "Veggie Pizza"; } } // PepperoniPizza.java class PepperoniPizza extends Pizza { public PepperoniPizza() { name = "Pepperoni Pizza"; } }
3. Create the Factory
// PizzaFactory.java class PizzaFactory { public Pizza createPizza(String type) { if (type.equalsIgnoreCase("cheese")) { return new CheesePizza(); } else if (type.equalsIgnoreCase("veggie")) { return new VeggiePizza(); } else if (type.equalsIgnoreCase("pepperoni")) { return new PepperoniPizza(); } else { System.out.println("Unknown pizza type: " type); return null; } } }
4. Use the Factory in Main
// Main.java public class Main { public static void main(String[] args) { PizzaFactory factory = new PizzaFactory(); Pizza pizza = factory.createPizza("cheese"); if (pizza != null) { pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); } } }
Output:

Preparing Cheese Pizza Baking Cheese Pizza Cutting Cheese Pizza Boxing Cheese Pizza
? Key Benefits
- Loose Coupling : The client (Main) doesn't need to know how to create a pizza — just ask the factory.
- Easy to Extend : Add a new pizza? Just create a new class and update the factory (or better, use a map/config for zero code change).
- Encapsulates Object Creation : All creation logic lives in one place.
?? Note: Simple vs. Factory Method Pattern
This is the Simple Factory pattern (not to be confused with the more formal Factory Method pattern, which uses inheritance). But it's a great starting point to understand the idea.
If you want full flexibility (eg, different factories for different regions), you'd go further with the Factory Method or Abstract Factory patterns.
Basically, the Factory pattern says: “Don't use new
everywhere — let a dedicated method or class decide what to create.”
The above is the detailed content of Can you explain the Factory design pattern with a simple example in Java?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

The factory pattern is used to decouple the creation process of objects and encapsulate them in factory classes to decouple them from concrete classes. In the Java framework, the factory pattern is used to: Create complex objects (such as beans in Spring) Provide object isolation, enhance testability and maintainability Support extensions, increase support for new object types by adding new factory classes

The SpringMVC framework uses the following design patterns: 1. Singleton mode: manages the Spring container; 2. Facade mode: coordinates controller, view and model interaction; 3. Strategy mode: selects a request handler based on the request; 4. Observer mode: publishes and listen for application events. These design patterns enhance the functionality and flexibility of SpringMVC, allowing developers to create efficient and maintainable applications.

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

PHP design patterns provide known solutions to common problems in software development. Common pattern types include creational (such as factory method pattern), structural (such as decorator pattern) and behavioral (such as observer pattern). Design patterns are particularly useful when solving repetitive problems, improving maintainability, and promoting teamwork. In e-commerce systems, the observer pattern can realize automatic updates between shopping cart and order status. Overall, PHP design patterns are an important tool for creating robust, scalable, and maintainable applications.

The factory pattern in PHP allows to generate objects without specifying the exact class. It is suitable for creating a large number of objects without knowing the actual category: defining the Product interface and specific product classes such as ProductA and ProductB. The Create Factory class provides the createProduct method to create the corresponding product by specifying the type (such as 'A'). Use Factory::createProduct('A') to create the required type of product to improve code maintainability, reusability and dynamic creation flexibility.
