Home > Article > Backend Development > Which scenarios in actual development require the use of the factory pattern?
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? . .
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 '传输参数有误,不属于任何一个职位'; 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
字段,但这个字段因为某些业务原因,需要使用整数来表示状态。那么,如果数字少了还好办,如果数字多了,上层使用者就不一定能记清楚每个数字代表的状态(比如你要做语音通信系统,那么,语音设备是有很多状态数字的)。这时,如果使用 new
来创建对象,然后再对 Status
进行赋值,不可避免的,可能要查阅开发文档,或者会不小心给出一个错误的值。这时,你就不妨使用工厂模式,或者其它合适的设计模式,来进行代码的建设。
比如,这样:
<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>
当然,使用枚举也行,这个说白了,就是看设计者的意愿了。
所以,设计模式没有说必需在哪个场景中使用,更确切的说,应该是,当你使用了设计模式,能不能为你的团队成员带来方便,或者提升代码质量,避免一些错误。如果是,就用,如果仅仅带来了复杂,并没有益处,那还是算了。
一句话,没有该不该用,也没有哪些需要不需要用,用就要带来效益,无论是对团队还是产品质量或产品的可维护性。用不用,要以团队配合和产品为导向,这才是对一个软件设计师的基本要求。
工厂的职能就是你给它一个模型或者具体的样品需求,它给你一个成品。工厂模式也是这样的道理,比如,你入参是a,它就给你一个A对象,你入参b,它就给你生产一个B对象,这里a,b就是你让工厂生产的商品具体需求,如长宽高等。
工厂模式还是很常见的,你没用到可能是因为项目规模小,或者是类不够抽象。
工厂你可以理解为隐藏了内部细节,你调用工厂的生产API ,直接获得所描述的物体,具体怎么生产的,你不用去关注细节,因为有的东西简单,直接new出来就可以了,但有的很复杂,比如spring的注入链。要理解工厂模式,建议看看spring实现的factory。