Policy mode:
Defines an algorithm family that encapsulates each algorithm, allowing them to be replaced by each other, which allows the algorithm to change independently of the client using the algorithm.
Structure diagram:
C + + implementation:
classCalculatestrategy { Public: Virtual intCalculateintValue1,intvalue2) =0;};classPlus: PublicCalculatestrategy { Public: intCalculateintValue1,intvalue2) {returnValue1 +value2;}};classMinus: PublicCalculatestrategy { Public: intCalculateintValue1,intvalue2) {returnValue1-value2;}};classCalculator {Private: Calculatestrategy*CS; Public: Calculator (calculatestrategy*strategy): CS (strategy) {}intCalculateintValue1,intvalue2) { returnCs->Calculate (value1, value2); } voidSetstrategy (Calculatestrategy *strategy) {cs =strategy;}; ~calculator () {DeleteCS;}};intMain () {Calculatestrategy*strategy =NewPlus; Calculator cal (strategy); cout<< Cal.calculate (1,2) <<Endl; Deletestrategy; Strategy=Newminus; Cal.setstrategy (strategy); cout<< Cal.calculate (1,2) <<Endl; //Delete strategy;}
Policy mode (strategy pattern)