[Design mode] Abstract Factory mode of javascript
Abstract Factory mode description 1. factory method mode: In the factory method mode, all creation classes must pass the factory class. If you want to extend the program, you must modify the factory class, which violates the closure principle, it is open to extensions and closed to modifications; it has some design problems. 2. How to solve the problem: the abstract factory mode is used to create a factory class for the function class separately, so that you do not have to modify the previous Code and extend the function. 3. the factory mode is actually to create and call a uniform factory method to implement the same interface class, but javascript does not have this interface, so this layer of implementation is removed, however, the members and methods of the bit function class should be the same. Example 1 of abstract factory source code. email sending class: copy the code function MailSender () {this. to = ''; this. title = ''; this. content = '';} MailSender. prototype. send = function () {// send body} copy Code 2. SMS sending class: copy the code function SmsSender () {this. to = ''; this. title = ''; this. content = '';} SmsSender. prototype. send = function () {// send body} copy code 3. here is the creation Factory interface class, which is removed here; directly create various functional factory; 1>. email Factory: function MailFactory () {} MailFactory. prototype. produce = function () {return new MailSender ();} 2>. SMS Factory: function SmsFactory () {} SmsFactory. prototype. produce = function () {return new SmsSender ();} 4. usage: var factory = new MailFactory (); var sender = factory. produce (); sender. to = 'toname # mail.com '; sender. title = 'abstract factory mode'; sender. content = 'send content'; sender. send () Other instructions in object-oriented languages such as java ,. net C # uses the factory mode and interfaces, which are available methods exposed to various users. This shows how to use this function to apply some methods. Objects are represented in the form of classes, representing an abstraction in the real world. There may be many similar applications, such as sending emails, sending text messages, and various promotion methods in malls, and various birds and animals in the animal world .. if we do not provide users with the interface form, it is bound to provide users with exposing real function class objects. Users can modify and expand class objects at will, which is not allowed. The factory method mode and the abstract factory mode can solve such problems well. Users can only use interfaces to call factory classes to perform specified operations. The Abstract Factory mode makes it easier to use extended functions, both the function class and the factory class implement their own class-level extension on the corresponding interface, and do not involve modification to other classes or methods;