search
HomeJavajavaTutorialDetailed explanation of common design patterns in Java-factory pattern

Principles of design patterns: For excuse programming

The role of the factory pattern:

A. In the design of the application, the creation of objects is concentrated in one place or unified and managed by a certain class (spring)

B. In Objects can be added directly without modifying the application, which also facilitates object maintenance.

Types of factory pattern:

                                                                    ‐ ’ s ’ s ’ s ’ s- with with swiss, Got it An experienced driver will instruct the driver to drive different cars to socialize on different occasions.

Simple factory:

abstract:

package com.product.abstruct;

public interface Car {

public void drive() ;//A car is meant to be driven, so it must have an engine

          }

T Implements:

Package com.product.implement;

Import com.product.abstruct.car;

Public Class Audi Implements Car {

Public Void Drive () {// BMW He is also a car or a horse, and he has to There is an engine

                                                                                                                                                                                                 }

                                                       

                                                                                                       

Implement; m Import com.product.abstruct.car;

public class benz images car {

public void drive () {// Audi is also a car, but also engine

// Todo Auto-Gen Eraate method stub

                           System.out.println("yes, today I am driving Benz..."); }

} = ====== Lamborghini Province ======

Factory class:

Factory class is a management class, the direct person in charge of the car, this person is the driver of the boss;

package com.product.factory;

                                                          import com.product.abstruct.Car; Public class Driver {

Public static Car driveCar(String carName) throws Exception{

                                                                                                                                                                      Benz (); return new Bwm();

                                                                          N Return New Audi ();

}}}

One day the boss wants to go to England to watch Liverpool's home game against Vela, and you need to play BMW to the airport, so he calls the driver and let him open BMW 2 pm BMW. pick him up. . .

                                                                                                  package com.product.test; public class Test {

                            public static void main(String[] args) throws Exception {

// Tell The Driver Which Car Wo Drive Todaty Wo Will to Amsterdam

Car Car = Driver.drivecar ("Benz"); drive();//One-click start

                                                                                                               As the boss’s business grew bigger and bigger, he became richer and richer, so he bought several sports cars. ---- Ferrari, Porsche, and Jaguar are three cars. Due to the increase in the number of cars, all the cars must be managed by an experienced driver. Annual inspections, insurance, tickets, and car washes are too much for the experienced driver alone, and the boss will give orders. The old driver has to drive different models of cars from Monday to Saturday. At this time, the old driver has to remember which car the boss needs to drive on which day, so he proposes to the boss: Hire a driver for each car. Each car has a dedicated person in charge. When you need to go out, just say hello to me, and I will send the corresponding person to pick up the boss. The boss said without hesitation: That’s it...

                                       :

package com.product.car.abstruct;

public interface car {

public void drive (); com. product.car.abstruct.Car;                  System.out.println("Four circles of wanting to be an official");

                              

                                                                                                                                                     com.product.car.abstruct.Car; O System.out.println ("I want to be an official four circle");

                                                                                     

         

                                                                                                        package com.product.car.manager; Car.abstruct.Car;                                                                                                                          does not need to be .product.car.abstruct.Car; public class AudiManager implements CarManager {

                                                                                                                                      public Car driveCar() {

                                                                                                          return new AudiDriver();                                                                                                    did the new Mercedes-Benz driver: ; Or Import com.product.car.implement.benzdriver;

import com.product.manager.Carmanager; C Car Drivecar () {

Return new BenzDriver();

                                                                                            package com.product.test;

                               import com.product.car.abstruct.Car; .car.implement.benzdriver;

Import com.product.Car.Carmanager; ON {

// Find a car supervisor , told him that I want to drive a BMW to watch the match between Liverpool and Villa today

                                                                              CarManager carManager = (CarManager) new BenzDriver(); Home phone, fill up the BMW, BMW is coming

                                Car driveCar = carManager.driveCar();

                                          ’s ’           ’ s ’   ’ s ’ s ’ s ‐ to ‐ ‐ ‐ ‐ ‐ ‐‐ ‐ and to Car driveCar = carManager.driveCar();                                                         driveCar.drive(); Compare the differences between these two modes and their respective advantages,

Programming perspective:

a. A simple factory has no abstract class, only one factory class. The parameters that need to be created are passed over, and the factory class creates them uniformly.

b. Define an interface for creating product objects. This interface plays this core role. He only needs to define the methods that subclasses must implement, and hand over the object to the object itself to create

Advantages and Disadvantages:

a. The factory method is more abstract than the simple factory method. The advantage of this is that it can easily add new members (recruit more drivers) without changing the role of the factory (without firing the old driver or reassigning him);

b. The advantage of a simple factory is that it is simple. It only creates corresponding objects based on parameters, but its disadvantages are also quite obvious. All objects are created in this class, and the objects created can only be known in advance ( Suddenly one day the boss bought a manual Jetta, and the boss had to inform the old driver that I bought a Jetta and put it in X); the addition of member objects will cause the core class to add methods, which violates high cohesion. When the system As the number of specific product categories in the product continues to increase, there may be a need for the factory class to create different instances according to different conditions. This kind of judgment of conditions and judgment of specific product types are intertwined, which makes it difficult to avoid the spread of module functions and is very detrimental to the maintenance and expansion of the system;

The next step is the application of the factory pattern. How can we be reasonable in program design? What about the application factory design pattern? a. For a certain product, the caller clearly knows which specific factory service should be used, instantiates the specific factory, and produces a specific product. This is the case with the iterator() method in Java Collection.

 b. Just need a product, but do not want to know or need to know which factory is producing it. That is, the final decision on which specific factory to use lies with the producer. They instantiate a specific product based on the current system situation. The factory is returned to the user, and this decision-making process is transparent to the user.

More Detailed explanations of common Java design patterns - Factory pattern related articles please pay attention to 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
Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Apr 19, 2025 pm 07:57 PM

Why can't the main class be found after copying and pasting the package in IDEA? Using IntelliJIDEA...

Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Apr 19, 2025 pm 07:54 PM

State synchronization between Java multi-interface calls: How to ensure that interface A is called after it is executed? In Java development, you often encounter multiple calls...

In Java programming, how to stop subsequent code execution when student ID is repeated?In Java programming, how to stop subsequent code execution when student ID is repeated?Apr 19, 2025 pm 07:51 PM

How to stop subsequent code execution when ID is repeated in Java programming. When learning Java programming, you often encounter such a requirement: when a certain condition is met,...

Ultimate consistency: What business scenarios are applicable to? How to ensure the consistency of the final data?Ultimate consistency: What business scenarios are applicable to? How to ensure the consistency of the final data?Apr 19, 2025 pm 07:48 PM

In-depth discussion of final consistency: In the distributed system of application scenarios and implementation methods, ensuring data consistency has always been a major challenge for developers. This article...

After the Spring Boot service is running for a period of time, how to troubleshoot?After the Spring Boot service is running for a period of time, how to troubleshoot?Apr 19, 2025 pm 07:45 PM

The troubleshooting idea of ​​SSH connection failure after SpringBoot service has been running for a period of time has recently encountered a problem: a Spring...

How to push the video stream of Hikvision camera SDK to the front-end Vue project for real-time playback?How to push the video stream of Hikvision camera SDK to the front-end Vue project for real-time playback?Apr 19, 2025 pm 07:42 PM

How to push video streams from Hikvision camera SDK to front-end Vue project? During the development process, you often encounter videos that need to be captured by the camera to be circulated...

How to limit access to access_token via OAuth2.0 scope parameter?How to limit access to access_token via OAuth2.0 scope parameter?Apr 19, 2025 pm 07:39 PM

How to use access_token of OAuth2.0 to restrict interface access permissions How to ensure access_token when authorizing using OAuth2.0...

In Spring Boot Redis, how to solve the problem of returning garbled codes?In Spring Boot Redis, how to solve the problem of returning garbled codes?Apr 19, 2025 pm 07:36 PM

SpringBootRedis gets the key garbled problem analysis using Spring...

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.