Home Java javaTutorial Factory Pattern

Factory Pattern

Nov 20, 2024 am 01:01 AM

What is Factory pattern?

Factory pattern is a creational pattern that defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory pattern lets a class defer instantiation to subclasses.

When to use it?

Use Factory pattern when you have "product" inheritance hierarchy and possibly add other products to that. (Product refers to an object that is returned by Factory method)

Problem

If you don't know about Simple Factory, I recommend to study it beforehand. There are plenty of resources but my blog is here.

Factory Pattern

Previously, we introduced Simple factory and we could produce variety of burgers while decoupling object creation from client code. Our burger shop has successfully earning profit and now we want to launch other burger shops in different area.

orderBurger method defines the process to sell a burger for a customer.

// This is our Client
public class BurgerShop {

    public Burger orderBurger(BurgerType type) {
        // Factory is responsible for object creation
        Burger burger = SimpleBurgerFactory.createBurger(type);

        burger.prepareBun();
        burger.grillPatty();
        burger.addToppings();
        burger.wrap();

        return burger;
    }
}

Copy after login
Copy after login

This is totally fine, but what if we launch other burger shops? Say we launch "SeaSideBurgerShop", we'll create SeaSideBurgerShop class and define its own orderBurger(). The problem is, they might forget to add toppings or do the process in the wrong order.

Problematic SeaSideBurgerShop:

public class SeaSideBurgerShop {

    public Burger orderBurger(BurgerType type) {
        Burger burger = SimpleBurgerFactory.createBurger(type);

        burger.prepareBun();
        burger.wrap(); // Wrap a burger before grilling a patty??
        burger.grillPatty();
        // They forget to add toppings!!

        return burger;
    }
}
Copy after login
Copy after login

To prevent this, we need a framework for our burger shops that define in which order they do the process and what to do, yet still allows things to remain flexible.

Solution

Factory Pattern

  1. BurgerShop
    This abstract class has two methods, orderBurger() and createBurger(). orderBurger() defines what to do and in which order the process should be done. This prevents burger shops to forget some process or mess up process order. creatBurger() is abstract method that lets subclasses determine which kind of burger gets made.

  2. BurgerShop subclasses
    These concrete BurgerShops are responsible for creating concrete burgers. Each subclass that extends BurgerShop defines its own implementation for createBurger().

  3. Burger
    This abstract class provides common interface among all the burgers and defines default behaviors.

  4. Burger subclasses
    Here are our concrete products. They can implement specific behavior by overriding methods as long as they extends Burger class.

Structure

Factory Pattern

Implementation in Java

// This is our Client
public class BurgerShop {

    public Burger orderBurger(BurgerType type) {
        // Factory is responsible for object creation
        Burger burger = SimpleBurgerFactory.createBurger(type);

        burger.prepareBun();
        burger.grillPatty();
        burger.addToppings();
        burger.wrap();

        return burger;
    }
}

Copy after login
Copy after login
public class SeaSideBurgerShop {

    public Burger orderBurger(BurgerType type) {
        Burger burger = SimpleBurgerFactory.createBurger(type);

        burger.prepareBun();
        burger.wrap(); // Wrap a burger before grilling a patty??
        burger.grillPatty();
        // They forget to add toppings!!

        return burger;
    }
}
Copy after login
Copy after login
public enum BurgerType {
    BEEF,
    CHICKEN,
    FISH,
    VEGGIE
}
Copy after login
public abstract class Burger {
    public BurgerType type;
    public List<String> toppings = new ArrayList<>();

    public void prepareBun() {
        System.out.println("Preparing a bun");
    }

    public void grillPatty() {
        if (type == null) {
            throw new IllegalStateException("pattyType is undefined");
        }
        System.out.println("Grill a " + type + " patty");
    }

    public void addToppings() {
        for (String item : toppings) {
            System.out.println("Add " + item);
        }
    }

    public void wrap() {
        System.out.println("Wrap a burger up");
    }
}
Copy after login
public class CityStyleBeefBurger extends Burger {

    public CityStyleBeefBurger() {
        type = BurgerType.BEEF;
        List<String> items = List.of("lettuce", "pickle slices", "tomato slice", "BBQ sauce");
        toppings.addAll(items);
    }
}
Copy after login
public class CityStyleVeggieBurger extends Burger {

    public CityStyleVeggieBurger() {
        type = BurgerType.VEGGIE;
        List<String> items = List.of("smoked paprika", "garlic chips", "crushed walnuts", "veggie sauce");
        toppings.addAll(items);
    }
}
Copy after login
public class SeaSideStyleBeefBurger extends Burger {

    public SeaSideStyleBeefBurger() {
        type = BurgerType.BEEF;
        // Localized toppings for beef burger in seaside area
        List<String> items = List.of("lettuce", "pickle slices", "tomato slice", "salty sauce");
        toppings.addAll(items);
    }

    // Uses localized wrapping paper
    @Override
    public void wrap() {
        System.out.println("Wrap with a paper with nice sea scenery");
    }
}
Copy after login
public class SeaSideStyleFishBurger extends Burger {

    public SeaSideStyleFishBurger() {
        type = BurgerType.FISH;
        // Localized toppings for fish burger in seaside area
        List<String> items = List.of("red onion slices", "salty sauce", "fried shrimps");
        toppings.addAll(items);
    }

    // Uses localized wrapping paper
    @Override
    public void wrap() {
        System.out.println("Wrap with a paper with nice sea scenery");
    }
}
Copy after login
public abstract class BurgerShop {

    // This method provides a framework for each burger shops to order burgers
    public Burger orderBurger(BurgerType type) {
        Burger burger = createBurger(type);

        burger.prepareBun();
        burger.grillPatty();
        burger.addToppings();
        burger.wrap();

        return burger;
    }

    // This is our factory method. Subclasses will override this method,
    // provide their own implementation, determine which kind of burger gets made.
    public abstract Burger createBurger(BurgerType type);
}
Copy after login

Output:

public class CityBurgerShop extends BurgerShop {

    @Override
    public Burger createBurger(BurgerType type) {
        return switch (type) {
            case BEEF -> new CityStyleBeefBurger();
            case VEGGIE -> new CityStyleVeggieBurger();
            default -> throw new IllegalArgumentException("unknown city burger type");
        };
    }
}
Copy after login

Pitfalls

  • Complex to implement because we need to create lots of classes that extends abstract creator or abstract product.

Comparison with Simple factory

  • In Simple factory, there is typically one factory class to decide which type of product to create, while Factory pattern may introduce multiple factories.
  • Simple factory often uses static method to create objects, which makes it easy to call but hard to extend. On the other hand, Factory method uses abstract method in super class, which acts as interface for all the factories and subclasses will provide concrete implementation for object instantiation.

You can check all the design pattern implementations here.
GitHub Repository


P.S.
I'm new to write tech blog, if you have advice to improve my writing, or have any confusing point, please leave a comment!
Thank you for reading :)

The above is the detailed content of Factory Pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles