Design Pattern series-factory method pattern

Source: Internet
Author: User

Review the article "factory model" in the Design Pattern series, which describes how to use the factory pattern to simulate a lightbulb change scenario: ordinary bulb, energy-saving bulb, color bulb. They are created by a single factory. When we need to use which bulbs, we only need to notify the factory class to create the same bulbs for us. The class diagram is as follows:

It can be seen from the above-side class diagram that all types of bulbs are created by the bulb factory. At this time, the bulb manufacturing plant needs to increase production because the company expands, at this time, a factory is definitely unable to cope with it, and there are many types of bulbs made by a factory, which increases the manufacturing pressure of the factory. At this time, the best way for enterprises to expand is, add factories to focus on the manufacture of only one bulb.

1. Factory method mode

First, let's take a look at what is the factory method model:Defines an interface used to create objects, so that the subclass determines which class to instantiate. The factory method delays the instantiation of a class to its subclass..

The factory method pattern class diagram is as follows:

Product: defines the interface of the object created by the factory method. It is equivalent to the light bulb abstraction in the above scenario.

Concreteproduct: a specific product class that implements product abstraction. It is equivalent to a specific lightbulb in the preceding scenario.

Creator: Declares the factory method. This method returns an object of the product type.

Concretecreator: The redefinition factory method returns a concreteproduct instance.

It may be a bit fuzzy after reading this class chart, but it doesn't matter. Next we will use the factory method mode to implement the above scenario (more factories need to be built for enterprise expansion ).

First, enterprises need to increase production to create more factories. To improve production efficiency, each factory only focuses on producing a variety of bulbs, the class diagram designed using the factory method pattern is as follows:

Code for edge analysis and implementation:

The first step is to expand the factory, and the products made are still bulbs. Therefore, we need to abstract the bulbs first. For more information, see the article "factory model.

// Lightbulb conventions
Public interface ibulb
{
// Unified luminous Interface
Public void luminescence ();
}

Step 2: implement the specific bulb types of all types currently. The Code is as follows:

// Light bulb
Public class bulb: ibulb // implements the conventions and standards of the bulb {
// Glow
Public void luminescence ()
{
// Lightbulb luminous implementation
}
}
// Energy-saving bulb
Public class frugalbulb: ibulb // implements the Convention and standard of the light bulb.
{
// Energy-saving light
Public void luminescence ()
{
// Energy-saving lightbulb luminous implementation
}
}
// Color light bulb
Public class colorbulb: ibulb
{
// Color light
Public void luminescence ()
{
// Realization of color light bulb
}
}

Step 3, because a factory is added, but each factory has a common behavior, that is, creating a light bulb. Therefore, to increase the factory more conveniently in the future, we abstract the factory. The Code is as follows:

// Factory Abstraction
Public interface imybulbfactory
{
Ibulb getbulb (); // in the future, every factory will make bulb.
}

Step 4: create a specific factory for each type of bulb. Each factory only manufactures the bulb of its own type. The Code is as follows:

// A factory for manufacturing general bulbs
Public class bulbfactory: imybulbfactory
{
// This factory can only make common bulbs.
Public ibulb getbulb ()
{
Return new bulb ();
}
}

// Create a factory for energy-saving bulbs
Public class frugalbulbfactroy: imybulbfactory
{
// This factory can only manufacture energy-saving bulbs.
Public ibulb getbulb ()
{
Return new frugalbulb ();
}
}

// Create a factory for energy-saving bulbs
Public class colorbulbfactroy: imybulbfactory
{
// This factory can only manufacture color bulbs.
Public ibulb getbulb ()
{
Return new colorbulb ();
}
}

In this way, we can meet the problem of expanding the enterprise and increasing the output. We only need to go to the specific factory to obtain the corresponding bulb. The main function is called as follows:

Static void main (string [] ARGs)
{
// The normal light bulb is required
Imybulbfactory bulbfactory = new bulbfactory ();
Ibulb bulb = bulbfactory. getbulb ();
Bulb. luminescence (); // normal bulb emits light

// Energy-saving bulbs required
Imybulbfactory frugalbulbfactroy = new frugalbulbfactroy ();
Ibulb frugalbulb = frugalbulbfactroy. getbulb ();
Frugalbulb. luminescence (); // energy-saving light bulb

// Color bulbs required
Imybulbfactory colorbulbfacroty = new colorbulbfactroy ();
Ibulb colorbulb = colorbulbfacroty. getbulb ();
Colorbulb. luminescence (); // color light bulb
}

Then we found that when the factory method delays the instantiation of a specific product to a specific factory class, when the client calls it, we must display which specific factory class to use, this increases the coupling degree.

2. Factory method mode using reflection

So how can we contact the above Coupling Degree? You can configure all factories in the current configuration file through the reflection mechanism of C #, and then configure a factory node to be used currently. The configuration file is as follows:

<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Deleetask>
<! -- Configure all existing factories -->
<Add key = "bulbfactory" value = "design mode series. Factory method mode. bulbfactory"> </Add>
<Add key = "frugalbulbfactory" value = "design mode series. Factory method mode. frugalbulbfactroy"> </Add>
<Add key = "colorbulbfactory" value = "design mode series. Factory method mode. colorbulbfactroy"> </Add>

<! -- Configure the factory currently in use. Currently, the factory value of the general lightbulb is "bulbfactory" -->
<Add key = "nonfactory" value = "bulbfactory"> </Add>
</Appsettings>
</Configuration>

We also need to encapsulate a class dedicated to providing specific factories. To facilitate this class, I will not consider coupling. The Code is as follows:

// It is used to provide the factory currently used by the current factory to be used and configured in the nonfactoty node in the configuration file
Public class factroyprovider
{
Public static imybulbfactory wheretofactroy ()
{
String fname = string. empty;
String factoryname = string. empty;
Imybulbfactory factory = NULL;

If (! String. isnullorempty (configurationmanager. etettings ["nonfactory"])
{
Factoryname = configurationmanager. etettings ["nonfactory"];
If (! String. isnullorempty (configurationmanager. configurettings [factoryname])
{
Fname = configurationmanager. etettings [factoryname];
Factory = assembly. Load ("design pattern series"). createinstance (fname) as imybulbfactory;
}
}

Return factory;
}
}

Find the factory through reflection. If we want to expand the company in the future, we only need to add specific factory instances and product instances and configure them in the configuration file.

3. Differences between the factory method mode and the factory Mode

Speaking of this, I don't know if you will have a question. In short, I have this question at the beginning. What is the difference between it and the factory model?

First, let's review the factory code in factory model. The Code is as follows:

Public class mybulbfactory
{
Public static ibulb getbulb (string bulbname)
{
Ibulb bulb = NULL;
// Tell me what you want, and I will make the corresponding bulb for you
Switch (bulbname)
{
Case "bulb ":
Bulb = new bulb ();
Break;
Case "frugalbulb ":
Bulb = new frugalbulb ();
Break;
Case "colorbulb ":

Bulb = new colorbulb ();
Break;
}
Return bulb;
}
}

It can be seen that if we need to add a light bulb in the future, we need to modify the factory class above and add a corresponding case Branch to the switch, which violatesOpen and closed PrincipleThe factory method is to delay the instantiation of these product types to specific factory classes for instantiation, in this way, if there is a new product in the future, you only need to create a new factory class and a specific product. That is to say, the factory method mode improves the simple factory mode, this satisfies the principle of openness and closure. However, the problem is that the client needs to specify the factory class to be instantiated each time it calls it. For example:

// The normal light bulb is required
Imybulbfactory bulbfactory = new bulbfactory (); // The specific factory class is defined here.
Ibulb bulb = bulbfactory. getbulb ();
Bulb. luminescence (); // normal bulb emits light

This increases coupling. We used the reflection class to lift coupling, but another question came out, so when creating a product class in the simple factory mode, if reflection is also used, the factory code will not need to be modified when new products are added in the future. That is to say, reflection can be perfectly solved in the simple factory mode.Open and closed PrincipleProblem!

So what is the role of the simple factory model when new problems arise?

I personally have two ways to understand it. It only represents my point of view. I also hope that you can talk about your point of view in detail ~!

First, when the programming language is not using the reflection mechanism in the early design mode, the factory method mode is used to upgrade the simple factory mode so that the open and closed principles can be supported.

Second, in special scenarios, the factory method mode can better implement logical organization, for example, the scenario used in this article.

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.