Design patterns - simple factory pattern Detailed

A simple factory pattern concept

  Simple factory pattern is part of creational design patterns, focused on the creation of objects.

  Let's consider a scenario of payment, take-away point in time, you can choose to use Alipay, micro-channel payment, ApplePay and other payment methods.

  These payments although the name is not the same, but the usage and procedures substantially similar, include legitimacy, security validation checking account payment environment to verify the payment password, debit account, the user pays notify the results of other functions.

  Have in common, we have an abstract base class, then all kinds of payment subclass inherits it, then implement your own business logic.

  If we want to use these payment methods, do not need to know the names of these specific subclass of payment, payment only need to know the name, the name passed to a method to return a corresponding object, at this time, you can use simple factory pattern.

Second, the realization

  1, first define an abstract class a variety of payment methods, simplicity defines the account to determine whether it is normal, payment, several methods to inform users

namespace SimpleFactory 
{ 
    the using the System; 

    public  abstract  class AbstractPaymentMethod 
    { 
        ///  <Summary> 
        /// determines whether the user's account normal
         ///  </ Summary> 
        ///  <param name = "of accountNumber"> account </ param> 
        / //  <Returns> account normal </ Returns> 
        public  abstract  BOOL IsAccountNormal ( String of accountNumber); 

        ///  <Summary> 
        /// inform the user
         ///  </ Summary> 
        ///  <param name = "Message">Notification content </ param>
        public abstract void NoticeUser(string message);

        /// <summary>
        /// 支付过程
        /// </summary>
        /// <param name="accountNumber">用户账号</param>
        /// <param name="amount">金额</param>
        public virtual void Pay(string accountNumber, decimal amount)
        {
            if (this.IsAccountNormal(accountNumber))
            {
                Console.WriteLine($""Account: {accountNumber} {amount} yuan has been paid);
                 The this .NoticeUser ($ ' Dear {accountNumber}, you have successfully paid {amount} Yuan " ); 
            } 
        } 
    } 
}

  2, to achieve Alipay, micro-channel pay

using System;

namespace SimpleFactory
{
    public class AliPay : AbstractPaymentMethod
    {
        public override bool IsAccountNormal(string accountNumber)
        {
            return true;
        }

        public override void NoticeUser(string message)
        {
            Console.WriteLine("支付宝支付");
            Console.WriteLine(message);
        }

    }
}
using System;

namespace SimpleFactory
{
    public class WeiXinPay : AbstractPaymentMethod
    {
        public override bool IsAccountNormal(string accountNumber)
        {
            return true;
        }

        public override void NoticeUser(string message)
        {
            Console.WriteLine("微信支付");
            Console.WriteLine(message);
        }
    }
}

  3, and then define a factory for creating these two payment. Factory method is determined here by an enumerated value (PaymentMethodEnum), to determine the required payment

namespace SimpleFactory
{
    using System;

    public class PaymentMethodFactory
    {
        public static AbstractPaymentMethod GetPaymentMethod(PaymentMethodEnum paymentMethod)
        {
            switch (paymentMethod)
            {
                case PaymentMethodEnum.AliPay:
                    return new AliPay();
                case PaymentMethodEnum.WeiXinPay:
                    return new WeiXinPay();
                default:
                    throw new NotImplementedException();
            }
        }
    }
}

Enum class

namespace SimpleFactory 
{ 
    public  enum PaymentMethodEnum 
    { 
        ///  <Summary> 
        /// Alipay
         ///  </ Summary> 
        AliPay = 0 , 

        ///  <Summary> 
        /// micro-channel payment
         ///  </ Summary> 
        WeiXinPay = . 1 
    } 
}

  4, analog client calls about

namespace SimpleFactory
{
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            AbstractPaymentMethod aliPay = PaymentMethodFactory.GetPaymentMethod(PaymentMethodEnum.AliPay);
            AbstractPaymentMethod weiXinPay = PaymentMethodFactory.GetPaymentMethod(PaymentMethodEnum.WeiXinPay);
            aliPay.Pay("Vincent", 700M);
            Console.WriteLine("*********************************");
            weiXinPay.Pay("123456", 1000M);
            Console.ReadKey();
        }
    }
}

  5, look at the results

  

Third, the summary

  Simple factory pattern of advantages:

  • Factory class contains the necessary logic judgment, can decide which instance of a product class is created at what time the client may be exempted from the responsibility to create product objects directly, but only "consumer" product; a simple factory pattern achieved through the practice of responsibility the division, which provides specialized factory class for creating objects.
  • Clients do not need to know the class name specific product category created only need to know the specific product class corresponding parameters can be, for some complex class name, a simple factory pattern can reduce the amount of user memory.
  • By introducing the configuration file, you can change and add new specific product category without modifying any client-side code and improve the flexibility of the system to some extent.

  Simple factory pattern drawbacks:

  • Since the factory class centralizes all product creation logic, once it does not work, the entire system must be affected.
  • Using a simple model will increase the number of factory classes in the system, increases the complexity and the difficulty of understanding the system in a certain program.
  • System expansion difficult, once the new product will have to add logic to modify the plant, when there are many types of products, may cause the plant logic is too complicated, is not conducive to the expansion and maintenance of the system.
  • Simple factory pattern due to the use of static factory method, resulting in the role of the factory can not form a hierarchy based on inheritance.

  Based on the above advantages and disadvantages, a simple factory pattern applies to the following scenarios:

  • Object factory class is responsible for creating relatively small: less due to the object created, the factory method will not cause too complex business logic.
  • The client only knows the parameters passed factory class, how to create objects do not care: the client requires neither care about the details of creation, even the name of the class do not need to remember that only need to know the type of the corresponding parameter.

  Download Code: https://github.com/hzhhhbb/SimpleFactory

Fourth, references

  https://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/simple_factory.html#id2

       

Guess you like

Origin www.cnblogs.com/hzhhhbb/p/11406771.html