


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!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics

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.

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

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.

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.

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

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

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.
