search
HomeJavajavaTutorialDetailed explanation of Java factory pattern: simple factory, factory method and abstract factory

Detailed explanation of Java factory pattern: simple factory, factory method and abstract factory

Dec 28, 2023 am 10:23 AM
Factory patternsimple factoryabstract factory

Detailed explanation of Java factory pattern: simple factory, factory method and abstract factory

Detailed explanation of Java factory pattern: simple factory, factory method and abstract factory

Factory pattern is a commonly used design pattern, which is used to dynamically create according to different needs Objects separate the creation and use of objects to improve code reusability and scalability. In Java, there are three main forms of factory pattern: simple factory, factory method and abstract factory.

1. Simple Factory Pattern
The simple factory pattern is the most basic factory pattern and the simplest form. It creates objects through a factory class and determines which type of object to create based on different parameters.

First, define an abstract product class, and all specific product classes inherit from this abstract class. Then, create a factory class that contains a static method that returns the corresponding specific product based on different parameters.

The following is a sample code to simulate the process of car production:

// 定义抽象产品类
abstract class Car {
    public abstract void produce();
}

// 定义具体产品类
class BenzCar extends Car {
    public void produce() {
        System.out.println("生产奔驰汽车");
    }
}

class BMWCar extends Car {
    public void produce() {
        System.out.println("生产宝马汽车");
    }
}

// 实现工厂类
class CarFactory {
    public static Car createCar(String brand) {
        if (brand.equals("Benz")) {
            return new BenzCar();
        } else if (brand.equals("BMW")) {
            return new BMWCar();
        } else {
            throw new IllegalArgumentException("Unsupported brand:" + brand);
        }
    }
}

// 测试代码
public class SimpleFactoryPatternDemo {
    public static void main(String[] args) {
        Car benz = CarFactory.createCar("Benz");
        benz.produce();

        Car bmw = CarFactory.createCar("BMW");
        bmw.produce();
    }
}

By calling the CarFactory.createCar method, car objects of different brands can be created according to different parameters.

The advantage of the simple factory pattern is that it is easy to understand and suitable for simple scenarios. But the disadvantage is that it violates the principle of openness and closure. When a new product is added, the code of the factory class needs to be modified.

2. Factory method pattern
The factory method pattern is an extension of the simple factory pattern. It introduces an abstract factory class to define methods, and specific product creation is implemented by subclass factory classes. Each concrete factory class is only responsible for creating one type of product.

First, define an abstract product class, which is also inherited by all concrete product classes. Then, create an abstract factory class that contains an abstract method for creating products. Each concrete factory class is responsible for creating a product.

The following is a sample code to simulate the process of mobile phone production:

// 定义抽象产品类
abstract class Phone {
    public abstract void produce();
}

// 定义具体产品类
class ApplePhone extends Phone {
    public void produce() {
        System.out.println("生产苹果手机");
    }
}

class HuaweiPhone extends Phone {
    public void produce() {
        System.out.println("生产华为手机");
    }
}

// 定义抽象工厂类
abstract class PhoneFactory {
    public abstract Phone createPhone();
}

// 定义具体工厂类
class ApplePhoneFactory extends PhoneFactory {
    public Phone createPhone() {
        return new ApplePhone();
    }
}

class HuaweiPhoneFactory extends PhoneFactory {
    public Phone createPhone() {
        return new HuaweiPhone();
    }
}

// 测试代码
public class FactoryMethodPatternDemo {
    public static void main(String[] args) {
        PhoneFactory appleFactory = new ApplePhoneFactory();
        Phone applePhone = appleFactory.createPhone();
        applePhone.produce();

        PhoneFactory huaweiFactory = new HuaweiPhoneFactory();
        Phone huaweiPhone = huaweiFactory.createPhone();
        huaweiPhone.produce();
    }
}

By implementing different specific factory classes, each factory class is responsible for creating a type of mobile phone object. Using the factory method pattern, you can easily add more product series without modifying existing code.

The advantage of the factory method pattern is that it complies with the open and closed principle. Each specific factory class is only responsible for creating one product and is easy to expand. But the disadvantage is that it increases the complexity of the system and requires a specific factory class to be defined for each product.

3. Abstract Factory Pattern
The abstract factory pattern is a continued extension of the factory method pattern. It introduces an abstract factory class to define a set of methods, each method is responsible for creating a product series. Each concrete factory class is responsible for creating a product family.

First, define an abstract product class and an abstract factory class. Each abstract factory class contains multiple abstract methods for creating products. Then, create specific product classes and specific factory classes, and implement abstract product classes and factory classes respectively.

The following is a sample code that simulates the process of producing TVs and refrigerators:

// 定义抽象产品类
abstract class TV {
    public abstract void produce();
}

abstract class Refrigerator {
    public abstract void produce();
}

// 定义具体产品类
class SamsungTV extends TV {
    public void produce() {
        System.out.println("生产三星电视");
    }
}

class TCLTV extends TV {
    public void produce() {
        System.out.println("生产TCL电视");
    }
}

class HaierRefrigerator extends Refrigerator {
    public void produce() {
        System.out.println("生产海尔冰箱");
    }
}

class GreeRefrigerator extends Refrigerator {
    public void produce() {
        System.out.println("生产格力冰箱");
    }
}

// 定义抽象工厂类
abstract class ApplianceFactory {
    public abstract TV createTV();
    public abstract Refrigerator createRefrigerator();
}

// 定义具体工厂类
class SamsungFactory extends ApplianceFactory {
    public TV createTV() {
        return new SamsungTV();
    }

    public Refrigerator createRefrigerator() {
        return new HaierRefrigerator();
    }
}

class TCLFactory extends ApplianceFactory {
    public TV createTV() {
        return new TCLTV();
    }

    public Refrigerator createRefrigerator() {
        return new GreeRefrigerator();
    }
}

// 测试代码
public class AbstractFactoryPatternDemo {
    public static void main(String[] args) {
        ApplianceFactory samsungFactory = new SamsungFactory();
        TV samsungTV = samsungFactory.createTV();
        Refrigerator haierRefrigerator = samsungFactory.createRefrigerator();
        samsungTV.produce();
        haierRefrigerator.produce();

        ApplianceFactory tclFactory = new TCLFactory();
        TV tclTV = tclFactory.createTV();
        Refrigerator greeRefrigerator = tclFactory.createRefrigerator();
        tclTV.produce();
        greeRefrigerator.produce();
    }
}

By implementing different concrete factory classes, each concrete factory class is responsible for creating a product series. Using the abstract factory pattern, you can easily add more product series without modifying existing code.

The advantages of the abstract factory pattern are that it conforms to the open and closed principle, is easy to expand, and can maintain the correlation between products. But the disadvantage is that when adding a new product series, the code of the abstract factory class needs to be modified.

Summary:
Factory pattern is a commonly used design pattern for dynamically creating objects according to different needs. There are three main factory patterns in Java: simple factory, factory method and abstract factory. The simple factory pattern is the most basic form. The factory method pattern introduces the abstract factory class on its basis. The abstract factory pattern extends the factory method pattern and introduces a set of methods to create a product series. Based on specific application scenarios and requirements, choosing the appropriate factory pattern can improve code reusability and scalability.

The above is the detailed content of Detailed explanation of Java factory pattern: simple factory, factory method and abstract factory. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function