


Which scenarios in actual development require the use of the factory pattern?
Jul 06, 2016 pm 01:51 PM
The factory method pattern allows the system to introduce new products without modifying the factory role.
Factory Mode
Simple Factory Pattern
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.
Factory Mode
Simple Factory Pattern
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
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è)務(wù)原因,需要使用整數(shù)來表示狀態(tài)。那么,如果數(shù)字少了還好辦,如果數(shù)字多了,上層使用者就不一定能記清楚每個數(shù)字代表的狀態(tài)(比如你要做語音通信系統(tǒng),那么,語音設(shè)備是有很多狀態(tài)數(shù)字的)。這時,如果使用 new
來創(chuàng)建對象,然后再對 Status
進行賦值,不可避免的,可能要查閱開發(fā)文檔,或者會不小心給出一個錯誤的值。這時,你就不妨使用工廠模式,或者其它合適的設(shè)計模式,來進行代碼的建設(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è)計者的意愿了。
所以,設(shè)計模式?jīng)]有說必需在哪個場景中使用,更確切的說,應(yīng)該是,當(dāng)你使用了設(shè)計模式,能不能為你的團隊成員帶來方便,或者提升代碼質(zhì)量,避免一些錯誤。如果是,就用,如果僅僅帶來了復(fù)雜,并沒有益處,那還是算了。
一句話,沒有該不該用,也沒有哪些需要不需要用,用就要帶來效益,無論是對團隊還是產(chǎn)品質(zhì)量或產(chǎn)品的可維護性。用不用,要以團隊配合和產(chǎn)品為導(dǎo)向,這才是對一個軟件設(shè)計師的基本要求。
工廠的職能就是你給它一個模型或者具體的樣品需求,它給你一個成品。工廠模式也是這樣的道理,比如,你入?yún)⑹莂,它就給你一個A對象,你入?yún),它就給你生產(chǎn)一個B對象,這里a,b就是你讓工廠生產(chǎn)的商品具體需求,如長寬高等。
工廠模式還是很常見的,你沒用到可能是因為項目規(guī)模小,或者是類不夠抽象。
工廠你可以理解為隱藏了內(nèi)部細節(jié),你調(diào)用工廠的生產(chǎn)API ,直接獲得所描述的物體,具體怎么生產(chǎn)的,你不用去關(guān)注細節(jié),因為有的東西簡單,直接new出來就可以了,但有的很復(fù)雜,比如spring的注入鏈。要理解工廠模式,建議看看spring實現(xiàn)的factory。

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w

UsemultilinecommentsinPHPforfunction/classdocumentation,codedebugging,andfileheaderswhileavoidingcommonpitfalls.First,documentfunctionsandclasseswith/*...*/toexplainpurpose,parameters,andreturnvalues,aidingreadabilityandenablingIDEintegration.Second,

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

Comments are an important part of CleanCode because they explain the intent behind the code rather than repeating the code. Good comments should appear in complex logic, non-intuitive conditional judgments, public API definitions, and to-dos; avoid meaningless descriptions, focus on explaining "why" and keeping them updated while using full sentence expressions. PHP supports three annotation formats: single line, multi-line and docblock. Docblock is not only beautiful, but can also be recognized by the IDE to improve team collaboration efficiency. Following framework specifications also contribute to project unity. Writing comments is not to make up the number of words, but to improve the readability and maintenance of the code and save future understanding costs.

Installing PHP is not complicated for novices. The key is to clarify the system environment and version requirements and follow the steps. First, you need to confirm the operating system (Windows, macOS or Linux) and choose a stable version such as PHP8.1 or 8.2; secondly, you can install it through manual installation, using integrated environments (such as XAMPP, WAMP) or package management tools (such as apt-get and brew). Then configure environment variables to ensure that the command line can recognize PHP instructions and run through the phpinfo() page test; finally pay attention to common problems, such as Apache port occupation, php.ini file path errors and extensions not enabled, etc., and check them one by one to complete the installation smoothly.
