The Strategy Mode is similar to the state mode, which uses delegation technically. However, the State mode uses the state as an object in semantics,
Describes the status changes of a class at runtime. The Strategy Mode treats an algorithm as an object to freely replace the algorithm at runtime. Their difference in structure is that the state mode usually has a reference to context (for example, in my state mode, context is trafficlight, but I did not include this reference in this example, because the example is too simple and unnecessary), when appropriate, the State object can call back the reference of this context, and strategy does not have this reference.
We now use the Strategy Mode to simulate error prompts during programming. Imagine: When an error occurs in our program, we may want to display the cause of the error to the user, but sometimes we want to record the error in the log, so users don't have to worry about it, this is two algorithms for error messages.
Let's take a look at the simulated code:
# Include <iostream>
# Include <string>
Using namespace STD;
// Define an interface first
Class strategy
...{
Public:
Virtual void output (string S) = 0;
};
Class showstrategy: public strategy
...{
Public:
Virtual void output (string S)
...{
// The output string is used for simulation, but it may be a function like MessageBox in the actual project.
Cout <"show strategy !! Error: "<S <Endl;
}
};
Class logstrategy: public strategy
...{
Public:
Virtual void output (string S)
...{
// Here the output string is used for simulation, but in the actual project, it may be to open the file, and then write the log record.
Cout <"log strategy !! Error: "<S <Endl;
}
};
// A context class using strategy
Class Context
...{
Public:
Void setstrategy (Strategy * s)
...{
_ S = s;
}
// Function. In reality, it may be a function that completes the actual function.
Void function ()
...{
// Call some other functions
// For example, openfile
// If an error occurs, the output is incorrect.
_ S-> output ("openfile failed! ");
}
PRIVATE:
Strategy * _ s;
};
Void main ()
...{
Context C;
Showstrategy SS;
Logstrategy ls;
// Use showstrategy to bring up the dialog box
C. setstrategy (& SS );
C. function ();
// Use logstrategy to record error logs
C. setstrategy (& LS );
C. function ();
}
Finally, the architecture of the Strategy and state modes is basically the same. Their core idea is to use delegated technology.
In fact, the design pattern skillfully uses various object-oriented features to combine the relationships between objects. These features include:
Combination, polymorphism, encapsulation, inheritance, delegation, etc.
So understanding these characteristics of object-oriented is the basis of the design model!