Design mode (a): Simple factory pattern

First, the schema definition

Simple factory pattern (Simple Factory Pattern): also known as static factory method (Static Factory Method) mode, which belongs to the class creates a schema. In the simple mode, the factory can return an instance of a different class according to different parameters. In simple terms, that is, it consists of a factory class to create an instance of the class of product which passed in accordance with the parameters decided.

Second, the model structure

 

(Photo blog: https://blog.csdn.net/xingjiarong/article/details/49999121 )

 

Simple factory pattern has three main components:

  • Factory class (Creator): This class is the core of a simple factory pattern, closely related to the business logic contained references.
  • This class is the parent class has a simple factory pattern created object, or they jointly owned interfaces: an abstract class (AbstractProduct).
  • Embodied (ConcreteProduct): This class is a simple object factory class instance model.

Third, the sample code

Here the code is divided into two versions iteration, the second version is the final version, you can directly view. Code for function only addition and subtraction between the digital.

Version 1: This version will separate business logic and interface logic :

///  <Summary> 
/// The version of the operational type of packaging, without regard to the input error
 ///  </ Summary> 
public  class VersionOne
{
    public void GetResult()
    {
        try
        {
            Console.WriteLine ( " Please enter the number A: " );
             String strNumberA = Console.ReadLine ();
            Console.WriteLine ( " Please select the operation symbol (+, -, *, /) " );
             String strOperate = Console.ReadLine ();
            Console.WriteLine ( " Please enter the number B: " );
             String strNumberB = Console.ReadLine ();
             String strResult = "" ;
            strResult = Convert.ToString(OperationVerOne.GetResult(Convert.ToDouble(strNumberA), Convert.ToDouble(strNumberB), strOperate));
            Console.WriteLine ( " the result is: " + strResult);
            Console.ReadKey();
        }
        catch (Exception e)
        {
            Console.WriteLine ( " you entered is wrong " + e.Message);
        }
    }
}

public class OperationVerOne
{
    public static double GetResult(double numberA, double numberB, string operate)
    {
        double result = 0d;
        switch (operate)
        {
            case "+":
                result = numberA + numberB;
                break;
            case "-":
                result = numberA - numberB;
                break;
            case "*":
                result = numberA * numberB;
                break;
            case "/":
                result = numberA / numberB;
                break;
        }

        return result;
    }
}

Version two , implement arithmetic operations separated by inheritance operated to comply with the open - closed principle, and by the plant operator to achieve:

class VersionTwo
{
   public
void Operation() { OperationTwo oper; Console.WriteLine ( " Please enter the number A: " ); String strNumberA = Console.ReadLine (); Console.WriteLine ( " Please select the operation symbol (+, -, *, /) " ); oper = OperationFactory.createOperation(Console.ReadLine()); Console.WriteLine ( " Please enter the number B: " ); String strNumberB = Console.ReadLine (); oper.NumberA = Convert.ToDouble(strNumberA); oper.NumberB = Convert.ToDouble(strNumberB); double result = oper.GetResult(); Console.WriteLine ( " the result is: " + Result); Console.ReadKey(); } } // the factory class
// Create operation corresponding to the class by passing parameters
public class OperationFactory { public static OperationTwo createOperation(string operate) { OperationTwo oper = null; switch (operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; } return oper; } } // Operation class, the base class public class OperationTwo { private double _numberA = 0; private double _numberB = 0; public double NumberA { get { return _numberA; } set { this._numberA = value; } } public double NumberB { get { return _numberB; } set { this._numberB = value; } } public virtual double GetResult() { double result = 0; return result; } } // Math class class OperationAdd: OperationTwo { public override double GetResult() { double result = 0; result = this.NumberA + this.NumberB; return result; } } class OperationSub : OperationTwo { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } class OperationMul : OperationTwo { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } class OperationDiv : OperationTwo { public override double GetResult() { double result = 0; result = NumberA / NumberB; return result; } }

 The example in FIG UML

Fourth, the advantages and disadvantages

  • Advantages: factory class is the key to the whole model contains the necessary logic judgment, according to outside information given to determine whether an object which specific classes should be created by using the factory class, the outside world can be embarrassing situation from directly create product-specific objects. get out, just need to be responsible for "consumer" objects on it. And do you need these objects exactly how to create and how to organize. Clear the respective responsibilities and rights, help to optimize the entire software architecture.
  • Disadvantages: As the factory class focused on creating a logical all instances of violation of the principle of high cohesion allocation of responsibilities, all to create a logical focus a factory class; it can only be created in advance taking into account the class, if you need to add the new class, we need to change the factory class. When the system is in specific product categories growing time, there may be requirements created by the factory needs of different instances according to different criteria. This judgment and the judgment of the conditions of the specific type of product intertwined, it is difficult to avoid the spread of module functions, the maintenance and expansion of the system is very unfavorable;

Fifth, usage scenarios

  • Object factory class is responsible for creating relatively small;
  • Customers only know the parameters passed factory class, how to create objects (logic) do not care;
  • It is generally applied only in very simple cases due to the simple factory was easily violated the principle of high cohesion allocation of responsibilities.

Github code: https://github.com/gp112/DesignPattern

reference:

"Westward Design Patterns"

Blog: https://blog.csdn.net/xingjiarong/article/details/49999121

 

Guess you like

Origin www.cnblogs.com/gp112/p/11072348.html