C ++ design pattern-comparison of simple factory pattern and strategy pattern

The simple factory pattern should have been introduced in the blog of the factory pattern, because there is a certain similarity with the strategy pattern, which is extracted here into a separate chapter.

Simple factory pattern

The process of creating an instance with a separate class is the factory.

Basic code

#include <iostream>
using namespace std;

class AbstractProduct {
public:
    virtual ~AbstractProduct() {} 
    virtual void Operation() = 0;
};

class ProductA : public AbstractProduct {
public:
    void Operation() { cout << "ProductA" << endl; }
};

class ProductB : public AbstractProduct {
public:
    void Operation() { cout << "ProductB" << endl; }
};

class Factory {
public:
    AbstractProduct* createProduct(char product) {
        AbstractProduct* ap = NULL;
        switch(product) {
            case 'A': ap = new ProductA(); break;
            case 'B': ap = new ProductB(); break;
        }
        return ap;
    }
};

int main() {
    Factory* f = new Factory();
    AbstractProduct* apa = f->createProduct('A');
    apa->Operation();  // ProductA

    AbstractProduct* apb = f->createProduct('B');
    apb->Operation();  // ProductB

    delete apa;
    delete apb;
    delete f;

    return 0;
}

Simple computing factory

class OperationFactory
{
public:
    Operation createOperate(string operate)
    {
        Operation 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;
    }
};

 

Comparison of simple factory model and strategy model

See this UML diagram to recall the strategy pattern I learned before

The two seem to be similar?

 

The only difference is the simple factory class and the Context class.

The original blog is implemented in Java. Since it does not affect reading and understanding, it is copied directly here without modification.
 
Simple factory class code and the class distinction Context

simple factory class:
public class OperationFactory
{
    public static Operation CreateOperate (string operate)
    {
        Operation oper=null;   
        switch (operate)
        {
            case "+":
                oper = new OperationAdd();
                break;
            case "-":
                oper = new OperationSub();
                break;
            case "*":
                oper = new OperationMul();
                break;
            case "/":
                oper = new OperationDiv();
                break;
            default:
                oper = new Operation();
                break;
        }
        return oper;
    }
}

 

The Context class in the strategy pattern:
class Context 
{ 
    CashSuper csuper; 
    public Context (CashSuper cs) 
    { 
        this .csuper = cs; 
    } 
    public  double GetResult ( double money) 
    { 
        // Call the charging method of the specific strategy class 
        return csuper.acceptCash (money); 
    } 
}

 


1. First look at the received parameters: the CreateOperate method in the simple factory class receives a string and returns an Operation object; and the Context class needs to receive a CashSuper object when it is initialized.
2. In the simple factory class, a corresponding object is created according to the received conditions, while the Context class receives an object, and you can call methods to execute the methods of this object.
Summarizing the simple factory pattern and the strategy pattern

1. In terms of types: the simple factory pattern belongs to the creation pattern, while the strategy pattern belongs to the behavior pattern.
2. Next, look at a small example:

 there are many types of axe, there is a factory specializing in the production of axe of various needs.

    Factory mode:
    1) According to the purpose you give to produce axes with different uses, for example, to cut people, then the factory produces axe for cutting people, and if you want to log, you produce axe for logging.
    2) A type of object that produces different behaviors according to some attributes you give back to you.
    3) Focus on the object creation
    strategy mode:
    1) Use the axe produced by the factory to do the corresponding things, for example, use the axe to cut people, and use the axe to cut wood.
    2) The corresponding method is executed according to the corresponding object you give.
    3) The choice of attention behavior

3. Simple factory model: according to the conditions of customer selection, to help customers create an object.
 Strategy mode: The customer gives it a created object, and it helps the customer to do corresponding things.
Advantages and disadvantages of the two models

first look at the two modes of client code:
// Client in simple factory mode: 
Operation op;
 // 
Hand over to simple factory class to create object 
op = OperationFactory.CreateOperate ( " + " ); op.StrNumberA = 10 ; 
op.StrNumberB = 20 ;
 // Call the generated object Method 
double result = op.GetResult (); 
Console.WriteLine (result);
 
// Client in strategy mode: 
double total = 0 ;
 private  void btnOk_Click ( object sender, EventArgs e) 
{ 
    CashContext cc = null ;
     // client creates object 
    switch (cbxType.SelectedItem.ToString ()) 
    { 
        case : " Normal charge " : 
            cc = new CashContext ( new CashNormal ()); break ;
         case : " Over
             300 returns 100 " : 
            cc =new CashContext ( new CashReturn ());
             break ;  
         case : " Take 20% off " : 
            cc = new CashContext ( new CashRebate ());
             break ;   
    } 
    // Calculate the fee charged by the specific strategy and give it to the context class to execute the corresponding method , The client only needs to receive the returned value to 
    double acceptMoney = cc.GetResult (Convert.ToDouble (txtPrice.Text) * Convert.ToDouble (txtNum.Text));
     // Calculate the total cost 
    total + = acceptMoney; 
    listBox1.Items .Add ( " Unit price: " + txtPrice.Text + " 数量:" + txtNum.Text + " " + comboBox1.SelectedItem.ToString() + "总计:" + acceptMoney);
    lblResult.Text = total.ToString();
}

 

By comparing the code of the client, it is found that the
  simple factory pattern: the creation of the object is handed over to the simple factory class. The client only needs to enter the corresponding conditions, and is not responsible for the creation of the object, but it needs the client to call the method of the algorithm class. . But once you need to add a new operation class, such as open root operation, you have to modify the simple factory class.
  Strategy mode: The selection and creation of objects still need to be done by yourself, but the responsibility of calling methods is given to the Context class. Once a new strategy needs to be added, the client needs to be modified.

Therefore, the shortcoming of the simple factory model is that when new demand increases, the factory class needs to be modified frequently. Only the strategy mode is used. When new requirements increase, the client needs to be modified. The client still bears the responsibility of creating objects, and does not reduce the pressure on the client. To use these two modes together, you need to modify the Context class, which is not perfect anyway.

Guess you like

Origin www.cnblogs.com/wkfvawl/p/12695924.html