SoFunction
Updated on 2025-03-06

Detailed explanation of the C# factory model

What is the factory model?
Analogize the concept in life. When we need to make a phone call, we need a mobile phone, and we usually choose to buy it directly at the physical store where we sell our mobile phones. But in programming, when we need to call a method of a class (PhoneA or PhoneB), we often have to care about how it is new (see code segment 1). It's like we have to go to the factory and tell them how you want to produce a mobile phone I need. And we only care whether he can make a phone call, and how you do it is nothing to do. So this has the factory model. The factory model is actually to abstract a factory. I just need any mobile phone and buy it at which factory. I don't have to care about his production process, you just need to produce the mobile phone with the functions I want. So we need to introduce a simple factory so that we no longer have to care about how mobile phones are produced. See Code Snippet 2 for the implementation of specific codes
Copy the codeThe code is as follows:

public class Customer
{
    public void CallSomeOne(){
        PhoneA p1 = new PhoneA();
        ();
    }
}
public class PhoneA
{
    public void Call(){}
}
public class PhoneB
{
    public void Call(){}
}

Snippet 1: The usual way to call class methods
Copy the codeThe code is as follows:

using System;
namespace Example1
{
    public interface IProduct { }
    public class PhoneA : IProduct { }
    public class PhoneB : IProduct { }
    public class Factory
    {
        public IProduct Create()
        {
// The factory decides which subclass to instantiate.
            return new PhonetA ();
        }
    }
}
using System;
namespace Example1
{
    public enum Category
    {
        A,

    }
    public static class ProductFactory
    {
        public static IProduct Create(Category category)
        {
            switch (category)
            {
                case :
                    return new PhoneA();
                case :
                    return new PhoneB();
                default:
                    throw new NotSupportedException();
            }
        }
    }
}

Code Snippet 2: Implementation of Simple Factory Mode
Copy the codeThe code is as follows:

[TestMethod]
        public void Test()
        {
            Factory factory = new Factory();
            IProduct phone = ();   
            <Type>((), typeof(PhoneA));
        }

Snippet 3: Testing of simple factory mode
New questions
In fact, I just mentioned that as long as we only have a phone that can only make phone calls, I want to buy it in a physical store. I don’t care which factory is produced by it~ In a simple factory, we still need to care about which factory is produced by it (see code segment 3). So we implement a physical store in the code so that we don’t have to worry about which factory it produces it. So we need to introduce abstract factories, so that we only need to deal with physical stores and don’t care about which factory to find to get a mobile phone. For specific implementations, see Code Snippet 4. We can use configuration files to realize the selection of factories and product selection, because this article does not want to introduce other concepts, so we will not discuss them here.
Copy the codeThe code is as follows:

namespace Example2
{
    /// <summary>
/// Abstract factory type characteristic description
    /// </summary>
    public interface IFactory
    {
IProduct Create();  //  The factory method that each factory needs to have - create a product
    }
    /// <summary>
/// Type of physical factory
    /// </summary>
    public class FactoryA : IFactory
    {
        public IProduct Create()
        {
            return new PhoneA();
        }
    }
    /// <summary>
/// Type of physical factory
    /// </summary>
    public class FactoryB : IFactory
    {
        public IProduct Create()
        {
            return new PhoneB();
        }
    }
}
using System;
using ;
namespace Example2
{
    class Client
    {
        public void SomeMethod()
        {
IFactory factory = new FactoryA();   // While obtaining the abstract Factory, it generates dependence with FactoryA;
IProduct Phone = (); // The subsequent operations are only completed by abstract IFactory and IProduct
            // ...
        }
        private IFactory factory;
public Client(IFactory factory) // Inject IFactory through Setter
        {
            if (factory == null) throw new ArgumentNullException("factory");
            = factory;
        }
        public void AnotherMethod()
        {
            IProduct Phone = ();
            // ... ...
        }
    }
}

summary
1. The factory method model focuses on the creation method of the overall object.
2. The intention of the factory method is very clear. It delays the instantiation process of the class to the subclass and handes the work of new() to the factory for completion.
At the same time, an abstract factory definition is added to solve a series of physical factory problems with a unified general factory method. In the .NET platform, we can use configuration, generics and delegates to achieve classic pattern purposes while obtaining a looser construction process between factory types and client programs.