Bitter Factory Mode (Factory method pattern)

Source: Internet
Author: User
Referring to the factory, the work of the assembly line, constantly repeating, is really more than our yards farmers still bitter force.

Factory mode is also very high frequency, its official interpretation is: Define an interface for creating objects, let subclasses decide which class to instantiate. The factory pattern defers the instantiation of a class to its subclasses.


, there are two kinds of superuser and ordinary user in the system, define a public interface user class, define a public abstract factory class Abstractuserfactory, The Userfactory class implements the factory pattern by inheriting the Abstractuserfactory class implementation to create a method CreateUser of the user class, implementing the code as follows:

PHP code

<?php Abstract class Abstractuserfactory {public abstract function createUser (); } class Userfactory extends <span style= "FONT-SIZE:1EM; line-height:1.5; " >abstractuserfactory </span><span style= "FONT-SIZE:1EM; line-height:1.5; " >{</span> PHP Code Public Function CreateUser ($className) {try{if (class_exists ($clas              SName)) return new $className ();                  else{$error = "no class";              throw new Exception ($error);          }}catch (Exception $e) {echo ' Caught Exception: ', $e->getmessage (), "\ n";  }}} interface user{public function Getgrade ();      } class SuperUser implements user{Public Function Getgrade () {echo 1;      }} class Commonuser implements user{Public Function Getgrade () {echo 0;  }} $userFactory = new Userfactory (); $userFactory->createuser (' SuperusEr ')->getgrade ();    $userFactory->createuser (' Commonuser ')->getgrade (); Running Result: 10Caught Exception:no class

Advantages of the factory model:

1. Good encapsulation, the code structure is clear. An object creation is conditionally constrained, as a caller needs a specific product object, as long as the class name (or constraint string) of the product is known, without knowing the arduous process of creating the object, and reducing the coupling between the modules.

2. Scalability is very good. In the case of adding product classes, "embrace change" can be accomplished as long as the specific factory class is modified appropriately or a factory class is extended. For example, in the example above, you need to add a blue diamond user, you only need to add a Blueuser class, the factory class does not need to modify the task to complete the system expansion.

3. Shielding the Product class. This feature is very important, how the implementation of the product class changes, the caller does not need to care, it only needs to care about the interface of the product, as long as the interface remains unchanged, the system of the upper modules do not change.

4. A typical decoupling framework. High-level module values need to know the product of the abstract class, other implementation classes do not care, in line with the Dimitri Law, I do not need to communicate, but also in line with the dependency inversion principle, only rely on product class abstraction, of course, also in line with the Richter replacement principle, using product sub-class replacement product parent class, no problem!

Usage Scenarios for Factory mode:

1. The Factory mode is a substitute for the new object, so it can be used where all objects need to be generated, but it is prudent to consider whether to add a factory class to manage and increase the complexity of the code.

2. When a flexible, extensible framework is required, a factory model can be considered. All things are objects, and all things are product classes.

3. The factory model can be used in heterogeneous projects.

4. You can use test-driven development under the framework. For example, testing a class A requires that Class B, which has an association with Class A, be generated at the same time, we can use the Factory mode to virtual out Class B, to avoid the coupling between Class A and Class B. (currently Java has Jmock and Easymock, this scenario has been weakened).

Extension of Factory mode:

1. Simple Factory mode (PHP common)

A module only needs a factory class, there is no need to produce it, using static method can be, according to this request, we put the above example of abstractuserfactory modified,


The Abstractuserfactory abstract class is removed, and the CreateUser is set as a static class, simplifying the process of creating classes. The disadvantage is that the expansion of factory class is difficult, does not conform to the opening and shutting principle, but it is still a very practical design mode.

2. Upgrade to more than one factory class

Each product class corresponds to a creation class, and the benefit is that the responsibility for creating the class is clear and simple, but has a certain impact on scalability and maintainability. If you want to extend a product class, you need to create a corresponding factory class, which increases the difficulty of scaling. Because the number of factory classes and products is the same, the relationship between the two objects needs to be considered during maintenance.

Of course, a multi-factory approach is generally used in complex applications, and then a coordination class is added to avoid the caller interacting with each sub-factory, and the role of the coordination class is to encapsulate the sub-factory classes and provide a unified access interface to the high-level modules.

3. Alternate Singleton mode

This pattern is implemented by reflecting a class instantiation that defines a private, parameterless construction method. Visually, PHP is not yet implemented and is skipped here.

4. Deferred initialization

Once an object is consumed, it is not released immediately, and the factory class remains in its initial state, waiting to be used again. For PHP-interpreted languages, it can be extended to lazy-loading, where the class file is loaded when the factory class prepares to create a new object, rather than loading the possible classes every time the script executes.

  • 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.