Design Pattern-factory Model

Source: Internet
Author: User
Tags switch case

Essentially, this mode uses classes to encapsulate and split conditional branches (if else, switch case). The problem is that the condition class encapsulation is also very troublesome.

In fact, for more advanced languages, such as the Dynamic Language Python (through Eval, as shown in the following example) or FP language (through pattern match), this mode has no value at all.

 

Factory model Overview

Factory model, including simple factory, factory method, abstract factory, why is it called factory, because the products produced by the factory are of the same specifications (that is, the interfaces are consistent and have a unified base class ), otherwise, it is called a workshop.
The benefit of consistent specifications is code reuse. Based on the principles of polymorphism and ripple replacement, all code can be written based on the base class. when switching between different child classes, you do not need to change any code, because the child classes can completely replace the parent class according to the lee's replacement principle.

 

Simple factory Mode

The simple factory mode is a creation mode, also called the staticfactory method mode, but not one of the 23 gof design modes. The simple factory mode is determined by a factory object to create a product instance.
Scenario: In the customer code, you need to create different objects according to different situations.
In this case, a large number of IF... else... are used to determine whether different conditions are used to create different objects.
Is this good? Obviously not good. If you need to select a lot of objects, you need to add a large segment of conditional judgment in the Customer Code, seriously affecting readability, so that the Code is not highlighted. it also seriously affects maintenance and scalability. This code must be modified every time an object is added.
What should I do? The simplest way is to move this code to other places so that the client code is clear and readable. This is the simple factory mode.
This mode is actually a simple encapsulation of the object creation code, the responsibility of object creation (large section if... else ...) put it in a simple factory, and in the Customer Code, you only need to provide simple parameters to get the corresponding object, without caring about the object creation process.
The advantage of this mode is to implement the single responsibility principle and put complex object creation code in a dedicated factory class, so that the readability and maintainability of the Customer Code are greatly enhanced.
The disadvantage is that when many objects need to be created and the logic is complex, the readability and maintainability of the factory class are still relatively poor.

Public class simplefactory {public static mobile createmobile (string jsonename) {If (jsonename. equals ("Nokia") {new Nokia ();} else if (canonical ename. equals ("Motorola") {New Motorola ();} else {Throw new exception ("this type of mobile phone production is not supported yet! ");}}}

Customer Code,

Object = simplefactory. createmobile ('nokia ')

In this way, the customer can simply get the object, regardless of the specific object scenario process, and through simple modification of parameters, different objects can be obtained.

 

Factory method mode

The simple factory model actually transfers the problem and does not actually solve it. after the logic of the created object is moved from the customer code to the factory class, the factory class still violates the open and closed principle. Every time a new object is added, the Code must be modified. When many objects need to be created, conditional judgment can be very confusing, seriously affecting readability and maintainability. so how can we solve this problem? The idea is to convert a factory class into many factory classes. Since a long string of condition creation statements are put in a factory class, it is difficult to maintain them. in this case, the creation process of each object is abstracted into multiple specific factory classes (such ). this is in line with the open and closed principle. When adding an object, we only need to add a specific factory class and do not need to modify the code of the original factory class.

The customer code is like,

Object = simplefactory. createmobile ('Nokia')

Replace,

Ifactory factory = newNokiafactory()

Object = factory. createmobile ()

It can be seen that there is no difference between a simple factory and a factory for the customer code. when you need to switch objects, you only need to modify one code to achieve this. polymorphism can be used elsewhere to avoid code modification.

The advantage of the factory method is to make the factory class scalable and compliant with the open and closed principles.

The disadvantage is that when there are many objects to be created, a large number of specific factory classes need to be created.

 

Abstract Factory Model

Abstract FactoryThe number of factory classes is growing too fastIf a new factory class is generated for each new class, you can imagine it...

Therefore, if the newly created class has a certain level, we can use the method of adding the class method to reduce the generation of the factory class.

In the following example, if Nokia generates many products, such as mobile and TV, in factory mode, we need to create nokiamobilef, nokiatvf...

For abstract factories, the Nokia layer can be abstracted as an abstract factory class, and mobile and TV can be implemented as class methods.

Ifactory factory = newNokiafactory()

Object = factory. createmobile ()

Now Nokia not only has mobile products but also produces TV products, so it can be solved by adding class functions to avoid adding factory classes.
Factory. createtv ()

The disadvantages of the abstract factory model are obvious. It is quite troublesome to add a product. It is quite annoying to add the create interface to the abstract factory class and all the derived classes.

 

Factory model useless?

We have introduced the improvement ideas like simple factory --> factory method --> Abstract Factory mode, but it seems that the more complicated the change, the more extensibility, but the price seems to be a little higher. Is there a shortcut? |

Generally, there are no shortcuts, but this is sometimes because some languages support this feature... (I do not know how to describe this feature, the statement is executed dynamically ?), Such as reflection in. Net or eval in Python

With this feature, we have a new idea of removing a large number of conditional statements,

For example, if. NET is not familiar with python,

class NokiaMobile:    def __init__(self):        self.name = 'nokia5500'class MotoMobile:    def __init__(self):        self.name = 'moto1000'class SimpleFactory:    def __init__(self):        self.name = 'Mot'    def createMobile(self):        if self.name =='Nokia':            return NokiaMobile()        if self.name =='Moto':            return MotoMobile()        else:            print 'No this name'            return None    def createMobileEval(self):        class_name = self.name + 'Mobile()'        try:            object = eval(class_name)        except Exception, e:            print 'No this class'+ str(e)            object = None        return object

We can clearly see that in the createmobile function, we need to use a large number of conditional statements. As the brand increases, this function will become longer and more complex.

For createmobileeval, no matter how many brands you add, the current code is enough. With this language feature, it is very simple to solve the problem.

If you want to add a product, you only need to add a function, such as createtveval.

In order to switch the brand or brand series freely without changing any customer code, we can also put the switch (the desired brand name) in a global variable or configuration file. so perfect ......

With this method, there is no need to use the factory method or abstract factory. The mode is dead, and the technology is live ......

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.