Home Java javaTutorial 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

Dec 28, 2023 am 10:23 AM
Factory pattern simple factory abstract 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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

// 定义抽象产品类

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();

    }

}

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

// 定义抽象产品类

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();

    }

}

Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

// 定义抽象产品类

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();

    }

}

Copy after login

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 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)

What are the benefits of java factory pattern What are the benefits of java factory pattern Dec 25, 2023 pm 05:40 PM

The benefits of the Java factory pattern: 1. Reduce system coupling; 2. Improve code reusability; 3. Hide the object creation process; 4. Simplify the object creation process; 5. Support dependency injection; 6. Provide better performance; 7. Enhance testability; 8. Support internationalization; 9. Promote the open and closed principle; 10. Provide better scalability. Detailed introduction: 1. Reduce the coupling of the system. The factory pattern reduces the coupling of the system by centralizing the object creation process into a factory class; 2. Improve the reusability of code, etc.

What are the application scenarios of factory pattern in java framework? What are the application scenarios of factory pattern in java framework? Jun 01, 2024 pm 04:06 PM

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

How to apply factory pattern in Golang How to apply factory pattern in Golang Apr 04, 2024 am 11:33 AM

Factory Pattern In Go, the factory pattern allows the creation of objects without specifying a concrete class: define an interface (such as Shape) that represents the object. Create concrete types (such as Circle and Rectangle) that implement this interface. Create a factory class to create objects of a given type (such as ShapeFactory). Use factory classes to create objects in client code. This design pattern increases the flexibility of the code without directly coupling to concrete types.

An in-depth analysis of the Java factory pattern: distinguishing and applying the differences between simple factories, factory methods and abstract factories An in-depth analysis of the Java factory pattern: distinguishing and applying the differences between simple factories, factory methods and abstract factories Dec 28, 2023 pm 03:09 PM

Detailed explanation of Java Factory Pattern: Understand the differences and application scenarios of simple factories, factory methods and abstract factories Introduction In the software development process, when faced with complex object creation and initialization processes, we often need to use the factory pattern to solve this problem. As a commonly used object-oriented programming language, Java provides a variety of factory pattern implementations. This article will introduce in detail the three common implementation methods of the Java factory pattern: simple factory, factory method and abstract factory, and conduct an in-depth analysis of their differences and application scenarios. one,

The application of singleton mode and factory mode in C++ function overloading and rewriting The application of singleton mode and factory mode in C++ function overloading and rewriting Apr 19, 2024 pm 05:06 PM

Singleton pattern: Provide singleton instances with different parameters through function overloading. Factory pattern: Create different types of objects through function rewriting to decouple the creation process from specific product classes.

PHP Design Patterns: The Path to Code Excellence PHP Design Patterns: The Path to Code Excellence Feb 21, 2024 pm 05:30 PM

Introduction PHP design patterns are a set of proven solutions to common challenges in software development. By following these patterns, developers can create elegant, robust, and maintainable code. They help developers follow SOLID principles (single responsibility, open-closed, Liskov replacement, interface isolation and dependency inversion), thereby improving code readability, maintainability and scalability. Types of Design Patterns There are many different design patterns, each with its own unique purpose and advantages. Here are some of the most commonly used PHP design patterns: Singleton pattern: Ensures that a class has only one instance and provides a way to access this instance globally. Factory Pattern: Creates an object without specifying its exact class. It allows developers to conditionally

Research on three design methods of Java factory pattern Research on three design methods of Java factory pattern Feb 18, 2024 pm 05:16 PM

Explore Three Design Ideas of Java Factory Pattern Factory pattern is a commonly used design pattern for creating objects without specifying a specific class. In Java, the factory pattern can be implemented in many ways. This article will explore the implementation of three Java factory patterns based on different design ideas and give specific code examples. Simple Factory Pattern The simple factory pattern is the most basic factory pattern, which creates objects through a factory class. The factory class determines what kind of specific object should be created based on the client's request parameters. Below is a brief

Understand the factory pattern in PHP object-oriented programming Understand the factory pattern in PHP object-oriented programming Aug 10, 2023 am 10:37 AM

Understanding the Factory Pattern in PHP Object-Oriented Programming The factory pattern is a commonly used design pattern that is used to decouple the creation and use of objects during the process of creating objects. In PHP object-oriented programming, the factory pattern can help us better manage the creation and life cycle of objects. This article will introduce the factory pattern in PHP in detail through code examples. In PHP, we can implement the object creation and initialization process by using the factory pattern instead of directly using the new keyword. The advantage of this is that if changes need to be made in the future

See all articles