国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Reply content:
Home Backend Development PHP Tutorial Which scenarios in actual development require the use of the factory pattern?

Which scenarios in actual development require the use of the factory pattern?

Jul 06, 2016 pm 01:51 PM
c# c++ java php Design Patterns

The factory method pattern allows the system to introduce new products without modifying the factory role.

  1. Factory Mode

  2. Simple Factory Pattern

  3. Abstract Factory Pattern

In what situations is it used in actual development? Why do I feel that I rarely use these design patterns in current development? . .

Reply content:

The factory method pattern allows the system to introduce new products without modifying the factory role.

  1. Factory Mode

  2. Simple Factory Pattern

  3. Abstract Factory Pattern

In what situations is it used in actual development? Why do I feel that I rarely use these design patterns in current development? . .

Let me first talk about the examples that I have seen using the factory pattern:

In the general MVC framework, there is a basic DB database basic operation class
I call it DB class, and there is a baseModel class to inherit the db class
baseModel is the base class of all framework models and needs to be inherited. baseModel
baseModel already has methods for adding, deleting, checking and modifying the db class. baseModel is actually a database factory. Different models inherit baseModel and have object instances for operating different data tables. In this way, a basic class is used to complete the instance. It converts objects from different data tables, just like a factory. Passing different table names will return you different objects.
This is my understanding. If there is any mistake, please forgive me and correct me.

Factory pattern is a pattern used to instantiate objects. It is a way to replace the new operation with factory methods. Factory mode is everywhere in Java projects, because factory mode is equivalent to creating new instance objects. For example, in our system, we often need to keep logs. If the initialization work done when creating a logger instance may be a long piece of code, It may require initialization, assignment, data query, etc., which will cause the code to be bloated and ugly.

<code>    private static Logger    logger = LoggerFactory.getLogger(MyBusinessRPC.class);
    
 public static Logger getLogger(String name) {
    ILoggerFactory iLoggerFactory = getILoggerFactory();
    return iLoggerFactory.getLogger(name);
  }

public static ILoggerFactory getILoggerFactory() {
    if (INITIALIZATION_STATE == UNINITIALIZED) {
      INITIALIZATION_STATE = ONGOING_INITIALIZATION;
      performInitialization();
    }
    switch (INITIALIZATION_STATE) {
      case SUCCESSFUL_INITIALIZATION:
        return StaticLoggerBinder.getSingleton().getLoggerFactory();
      case NOP_FALLBACK_INITIALIZATION:
        return NOP_FALLBACK_FACTORY;
      case FAILED_INITIALIZATION:
        throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
      case ONGOING_INITIALIZATION:
        // support re-entrant behavior.
        // See also http://bugzilla.slf4j.org/show_bug.cgi?id=106
        return TEMP_FACTORY;
    }
    throw new IllegalStateException("Unreachable code");
  }</code>

If you want to understand the factory pattern, you must know the simple factory pattern.

<code> switch ($type) { 
      case '存款職員': $man = new Depositer; 
      break;
      case '銷售': $man = new Marketer; 
      break; 
      case '接待': $man = new Receiver; 
      break; 
      default: echo '傳輸參數(shù)有誤,不屬于任何一個職位'; 
      break; 
  }
</code>

No, this is the simple factory model. Is it very common? The simple factory model has a shortcoming. Although it follows the single responsibility principle, it violates another very important principle: Open and closed principle. If a new clerk position is added, then we have to modify the corresponding code and add a case. This is very scary, because if we modify the written code again, it may cause unknown effects.

The factory mode is an upgrade to the simple factory. Here is the DB class in MVC. When making an external call, you only need to select the table name you need, and the factory will call the real database processing method and then return the results you want.

Whether it is the factory pattern or other creation patterns, they all have one purpose - to initialize an object. In other words, in order to build a data structure model (classes and objects themselves are a custom data structure).

So, the question is, why can we create an object in this way and use design pattern? Essentially, the reason is that we don’t want upper-level users to directly use new to initialize objects. new

There are many reasons for this, most of which are that

isolates the object creation process from upper-level users; or the object creation process is complicated and difficult for users to master ; Or object creation must meet certain conditions . These conditions may be business needs or system constraints. There is no need for upper-level users to master them and increase the difficulty of development by others.

So, by now we should be clear, whether it is the factory mode or the opening and closing principle mentioned by the comrades above, it is to isolate some complex processes so that these complex processes are not exposed to the outside world. If they are exposed These processes will add trouble to users, which is called teamwork.

Object-oriented encapsulation itself is to make external

as simple as possible. API

例如,你定義了一個 Status字段,但這個字段因?yàn)槟承I(yè)務(wù)原因,需要使用整數(shù)來表示狀態(tài)。那么,如果數(shù)字少了還好辦,如果數(shù)字多了,上層使用者就不一定能記清楚每個數(shù)字代表的狀態(tài)(比如你要做語音通信系統(tǒng),那么,語音設(shè)備是有很多狀態(tài)數(shù)字的)。這時(shí),如果使用 new來創(chuàng)建對象,然后再對 Status 進(jìn)行賦值,不可避免的,可能要查閱開發(fā)文檔,或者會不小心給出一個錯誤的值。這時(shí),你就不妨使用工廠模式,或者其它合適的設(shè)計(jì)模式,來進(jìn)行代碼的建設(shè)。

比如,這樣:

<code>public static class Factory
{
    public static Ixxxxxx CreateWithOpen()
    {
        var obj = new Obj();
        obj.Status = 1;
        return obj;
    }
    public static Ixxxxxx CreateWithClose()
    {
        var obj = new Obj();
        obj.Status = 2;
        return obj;
    }
}
</code>

當(dāng)然,使用枚舉也行,這個說白了,就是看設(shè)計(jì)者的意愿了。

所以,設(shè)計(jì)模式?jīng)]有說必需在哪個場景中使用,更確切的說,應(yīng)該是,當(dāng)你使用了設(shè)計(jì)模式,能不能為你的團(tuán)隊(duì)成員帶來方便,或者提升代碼質(zhì)量,避免一些錯誤。如果是,就用,如果僅僅帶來了復(fù)雜,并沒有益處,那還是算了。

一句話,沒有該不該用,也沒有哪些需要不需要用,用就要帶來效益,無論是對團(tuán)隊(duì)還是產(chǎn)品質(zhì)量或產(chǎn)品的可維護(hù)性。用不用,要以團(tuán)隊(duì)配合和產(chǎn)品為導(dǎo)向,這才是對一個軟件設(shè)計(jì)師的基本要求。

工廠的職能就是你給它一個模型或者具體的樣品需求,它給你一個成品。工廠模式也是這樣的道理,比如,你入?yún)⑹莂,它就給你一個A對象,你入?yún),它就給你生產(chǎn)一個B對象,這里a,b就是你讓工廠生產(chǎn)的商品具體需求,如長寬高等。

工廠模式還是很常見的,你沒用到可能是因?yàn)轫?xiàng)目規(guī)模小,或者是類不夠抽象。

工廠你可以理解為隱藏了內(nèi)部細(xì)節(jié),你調(diào)用工廠的生產(chǎn)API ,直接獲得所描述的物體,具體怎么生產(chǎn)的,你不用去關(guān)注細(xì)節(jié),因?yàn)橛械臇|西簡單,直接new出來就可以了,但有的很復(fù)雜,比如spring的注入鏈。要理解工廠模式,建議看看spring實(shí)現(xiàn)的factory。

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How does a HashMap work internally in Java? How does a HashMap work internally in Java? Jul 15, 2025 am 03:10 AM

HashMap implements key-value pair storage through hash tables in Java, and its core lies in quickly positioning data locations. 1. First use the hashCode() method of the key to generate a hash value and convert it into an array index through bit operations; 2. Different objects may generate the same hash value, resulting in conflicts. At this time, the node is mounted in the form of a linked list. After JDK8, the linked list is too long (default length 8) and it will be converted to a red and black tree to improve efficiency; 3. When using a custom class as a key, the equals() and hashCode() methods must be rewritten; 4. HashMap dynamically expands capacity. When the number of elements exceeds the capacity and multiplies by the load factor (default 0.75), expand and rehash; 5. HashMap is not thread-safe, and Concu should be used in multithreaded

Why We Comment: A PHP Guide Why We Comment: A PHP Guide Jul 15, 2025 am 02:48 AM

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

How to Install PHP on Windows How to Install PHP on Windows Jul 15, 2025 am 02:46 AM

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

How to format a date in Java with SimpleDateFormat? How to format a date in Java with SimpleDateFormat? Jul 15, 2025 am 03:12 AM

Create and use SimpleDateFormat requires passing in format strings, such as newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); 2. Pay attention to case sensitivity and avoid misuse of mixed single-letter formats and YYYY and DD; 3. SimpleDateFormat is not thread-safe. In a multi-thread environment, you should create a new instance or use ThreadLocal every time; 4. When parsing a string using the parse method, you need to catch ParseException, and note that the result does not contain time zone information; 5. It is recommended to use DateTimeFormatter and Lo

PHP Syntax: The Basics PHP Syntax: The Basics Jul 15, 2025 am 02:46 AM

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

PHP remove whitespace from string PHP remove whitespace from string Jul 15, 2025 am 02:51 AM

There are three main ways to remove spaces in PHP strings. First, use the trim() function to remove whitespace characters at both ends of the string, such as spaces, tabs, line breaks, etc.; if only the beginning or end spaces need to be removed, use ltrim() or rtrim() respectively. Secondly, using str_replace('','',$str) can delete all space characters in the string, but will not affect other types of whitespace, such as tabs or newlines. Finally, if you need to completely clear all whitespace characters including spaces, tabs, and line breaks, it is recommended to use preg_replace('/\s /','',$str) to achieve more flexible cleaning through regular expressions. Choose the right one according to the specific needs

python if else example python if else example Jul 15, 2025 am 02:55 AM

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

Java for loop examples Java for loop examples Jul 15, 2025 am 03:07 AM

There are three common forms of Java for loops. 1. The basic for loop is suitable for cases where the number of loops is known. The syntax is for (initialization; conditional judgment; update), such as traversing arrays or counts; 2. The enhanced for loop (for-each) is used to simplify the traversal of arrays or collections, and the syntax is for (element type variable name: the object to be traversed), but the index cannot be accessed or the collection content cannot be modified; 3. Nested for loops are used to deal with two-dimensional structures such as matrices, outer control rows, and inner control columns, but performance issues need to be paid attention to.

See all articles