. NET Factory Method model explained

Source: Internet
Author: User
Factory Method Mode Introduction:

The meaning of the factory method mode is to define a factory interface that creates the product object and defer the actual creation to the subclass Factory. The Core factory class is no longer responsible for product creation, so that the core class becomes an abstract factory role and is responsible only for the interfaces that a specific factory subclass must implement, and the benefit of further abstraction is that the factory method pattern allows the system to introduce new products without modifying the specific factory roles.

Factory method Pattern Structure diagram:

Character Categories:

Abstract Factory Role: is the core of the factory method pattern, regardless of the application. Any factory class of objects created in the schema must implement this interface.
Specific factory roles: This is the specific factory class that implements the abstract factory interface, contains logic that is closely related to the application, and is called by the application to create the Product object
Abstract product role: The super type of the object created by the factory method pattern, which is the common parent or co-owned interface of the product object. In, this role is light.
Specific product role: This role implements the interface defined by the abstract product role. A specific product has a specific factory-created, often one by one correspondence between them.

Introduce practical examples:

In the previous blog Simple factory model, the following implementations were implemented using the simple factory model: if there is a household management system, the household type is variable, and the rent calculation formula for each tenant type is different for example: a type of household rent amount = days * unit price + performance *0.005;b type of household rent amount = Month * (monthly price +performance*0.001) Here we have achieved the customer's needs, but if the customer needs to add the C type store and the D type store later, and their algorithm requirements are different, this time we need to do c,d type store creation, and inherit the Ishop interface, implement the method inside, but also have to continue to modify the factory class in the SWITC add case to capture the creation of the corresponding store object, once this situation, is not conducive to the extension of the program and the maintenance of the project later.

1. Analysis: The store has a common behavioral characteristics, we have to carry out store rent calculation behavior, we abstracted the ishop, which is to be realized in the calculation of store rent method behavior.

Using system;using system.collections.generic;using system.linq;using system.text; Namespace factoryentiy{public  interface ishop  {    double getrent (int days, double dayprice, double performance);}  }

2. We implement the methods inside the Isho interface to create a type A, B shop.

Using factoryentiy;using system;using system.collections.generic;using system.linq;using System.Text; namespace productenity{///<summary>////  inherit the store interface, implement the behavior method inside, that is, the algorithm///  </summary>  Public Class Ashop:ishop  {    //<summary>///a type store rental amount, days * unit price + performance *0.005    //</summary>// /<param Name= "Days" > Nights </param>//    <param name= "Dayprice" > Daily price </param>//    < Param name= "Performance" > Daily average performance </param>//    <returns></returns> public    Double getrent (int days, double dayprice, double performance)    {      Console.WriteLine ("A shop's rent algorithm");      Return days * dayprice + performance * 0.01;    }}  }

Using factoryentiy;using system;using system.collections.generic;using system.linq;using System.Text; namespace productenity{///<summary>////  inherit the store interface, implement the behavior method inside, that is, the algorithm///  </summary>  Public Class Bshop:ishop  {    //<summary>//b Type store = month * (monthly price +performance*0.001)///    </summary >//    <param name= "Month" > Number of months </param>//    <param name= "Monthprice" > Monthly price </param> //    <param name= "Performance" > Monthly average performance </param>//    <returns></returns>    public double getrent (int month, double Monthprice, double performance)    {      Console.WriteLine ("B Shop Rent Algorithm");      Return month * (Monthprice + performance * 0.001);}}  

3. Now consider the circumstances under which the store entity is created, rents the different stores, and facilitates subsequent additions and modifications. So we created the Ifactroy interface, which is the way to create store objects.

Using factoryentiy;using system;using system.collections.generic;using system.linq;using System.Text; namespace factorymethod{///<summary>///  factory class, create store type entity///  </summary> public  interface Ifactory  {    ishop createshop ();}  }

4. Now we can inherit from ifactory to create the corresponding store object inside.

Using factoryentiy;using factorymethod;using productenity;using system;using system.collections.generic;using System.linq;using System.Text; namespace productenity{///<summary>///  Inherit factory class, create a Type store entity///  </summary> public  class Createbshop:ifactory  {public    ishop createshop ()    {      return new ashop ();  }}}

Using factoryentiy;using factorymethod;using productenity;using system;using system.collections.generic;using System.linq;using System.Text; namespace productenity{///<summary>///  Inherit factory class, create B Type store entity///  </summary> public  class Createashop:ifactory  {public    ishop createshop ()    {      return new bshop ();  }}}

5. Then, judging by the current store type, which algorithm should be used for this type of store:

Using factoryentiy;using system;using system.collections.generic;using system.configuration;using System.Linq;using System.reflection;using System.Text; Namespace factorymethod.app{class Program {static void Main (string[] args) {string shopname = Configuratio      nmanager.appsettings["Createshopclassname"]; Shopname to create the store class name, here =createashop ifactory af = (ifactory) assembly.load ("Productenity").      CreateInstance ("productenity." + shopname);      The first productenity is the name of the DLL, and the second productenity is the namespace of the project. Ishop as = af. Createshop (); Double total = as.getrent (30, 300, 2000);             30 days/100 Yuanri average performance is Console.WriteLine ("The Rent for the type a store is:" + total);      Console.WriteLine ("============="); Ifactory bf = (ifactory) assembly.load ("Productenity").      CreateInstance ("productenity." + "Createbshop");      Createbshop can be saved as a configuration or exists in the database,//Note that the save string should be the same as the class name created in the project,//Otherwise reflection will not find the class under that item. Ishop Bs = bf. Createshop (); Total = Bs.getrent (30, 300, 2000); 30 days/100 Yuanri average performance is 2000     Console.WriteLine ("The Rent for the type a store is:" + total); }  }}

Here we use the reflection method to create the object, replace the previous factory class by switch to create the object by the way, facilitates the subsequent new type store additions and algorithm modifications to increase and maintenance after the project needs in the change, we only need to re-add the C,d type store in the project, Inherit the ishop implementation of the method inside, at the same time, add the inherited Ifactroy interface, create the corresponding store object to compile the ProductEnity.dll of the project, and later to calculate the c,d type of store algorithm can be calculated by reflection method, You do not need to modify the original project class code.

The entire project is structured as follows:

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