Design pattern series -- strategy pattern

Posted by herschen on Thu, 17 Feb 2022 20:12:01 +0100

Tip: after the article is written, the directory can be generated automatically. Please refer to the help document on the right for how to generate it

example

Scenario:
Shopping mall cashier software, the salesperson charges the customer according to the unit price and quantity of the goods purchased by the customer.

1, Knowledge points

Strategy mode: it defines the algorithm family and encapsulates them separately so that they can be replaced with each other. This mode makes the change of the algorithm not affect the customers using the algorithm.

The simple factory mode uses factories to generate algorithm objects, that is, encapsulating algorithms. The algorithm itself is just a strategy. The most important thing is that these algorithms can replace each other at any time. This is the change point, and encapsulating the change point is a very important object-oriented thinking method

The policy mode is an improvement of the simple factory mode to reduce the coupling with the client.

Some codes of simple factory:

class OperationFactory {
	public:
		void createOperate(string operate);
}

OperationFactory:: void createOperate(string operate) {
	Operation* p;
	switch (operate) {
		case "+":
			p = new OperationAdd();
			break;
		case "-":
			p = new OperationSub();
			break;
		case "*":
			p = new OperationMul();
			break;
		case "/":
			p = new OperationDiv();
			break;
	}
	return p;
}

//Client code
int main() {
	Operation* per = OperationFactory.createOperate("+");
	p._numberA = 1;
	p._numberB = 2;
	double result = p.GetResult();
}

In the client code, use operationfactory The createoperate function makes logical judgments of different businesses, creates corresponding algorithm objects, and calls the methods of algorithm objects for operation. For the client, there are two interfaces.

If you re encapsulate a class context, the operationfactory The return of createoperate is used as a member variable Operation of class, and a member function getResult is defined to call Operation GetResult () is called by the client. In this way, you only need to call context (operate) Getresult().

context merges OperationFactory, removes complicated logical judgment, and also absorbs its results into member variables to build external interfaces.

The policy pattern is used to encapsulate the algorithm. When different business rules are applied at different times and different behaviors are stacked in a class, it is difficult to avoid using conditional statements to select the appropriate behavior. Encapsulate these behaviors in independent strategies and eliminate conditional statements in the classes that use these behaviors.

2, Code implementation

class CashContext
{
	CashSuper cs = null;
	
	// Package judgment logic
	public CashContext(string type)
	{
		case "Normal charge":
			CashNormal cs0 = new CashNormal(); // Omit the specific algorithm code
			cs = cs0;
			break;
		case "Return 100 after 300":
			CashReturn cr1 = new CashReturn("300","100"); // Omit the specific algorithm code
			cs = cr1;
			break;
		case "20% off":
			CashRebate cr2 = new CaseRebate("0.8"); // Omit the specific algorithm code
			cs = cr2;
			break;
	}
}

public double GetResult(double money)
{
	return cs.acceptCash(money);//Use the result of logical judgment and call its method
}

//Client code
double total = 0.0d;
private void btnOk_Click(object sender, EvenArgs e)
{
	CashContext csuper = new CashContext(cbxType.SelectedItem.ToString()); //Pass the options of the drop-down box into context
	double totalPrices = 0d;
	totalPrinces = csuper.GetResult(Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtNum.Text)); // Call the unified output function of context
	total = total + totalPrices;
	lbxList.Items.Add("Unit Price:" + txtPrice.Text + "number:" + txtNum.Text + " " + cbxType.SelectedItem + "total: " + totalPrices.ToString());
	lblResult.Text = total.ToString();
}

It is equivalent to encapsulating the work of the factory into the context, and taking the result of condition judgment as the member variable of the context, which reduces the number of calling interfaces of the client.

UML class diagram

Topics: Design Pattern