GOF "design pattern" is described in the strategy mode:
Define a series of algorithms that encapsulate them one by one and make them interchangeable with each other. The strategy mode allows the algorithm to vary independently from the customer who uses it.
The strategy model is based on the following principles:
1 Each object is an individual with responsibility.
2 The specific implementation of these responsibilities is accomplished through the use of polymorphism.
3 The concept of the same algorithm has a number of different implementations, need to be managed.
I'll use an example below to illustrate its specific usage, which is about database connectivity. The code is as follows:
interface databasestrategy{
public void process ();
}
Class Mysqldbstrategy implements databasestrategy{
public void process () {
System.out.println ("Processing MySQL number According to the Library Connection ");
}
}
Class Oracledbstrategy implements databasestrategy{
public void process () {
SYSTEM.OUT.PR INTLN ("Process Oracle database Connection");
}
}
class databasemanager{
public void process (Databasestrategy dbstrategy) {
Dbstrategy.proce SS ();
}
}
Publicclass strategyclient {
public static void Main (string[] args) {
Mysqldbstrategy Mys Ql=new Mysqldbstrategy ();
Databasemanager manager=new Databasemanager ();
Manager.process (MySQL);
Oracledbstrategy oracle=new oracledbstrategy ();
Manager.process (Oracle);
}
}
In our actual programming will often encounter the system to connect the database may be more than one, if the traditional method, that is, modify the connection URL method, this method is indeed feasible, but there is a problem to often modify the source code, not conducive to future maintenance, then there is a better way? The answer is yes, using the strategy pattern, first define a common interface to the database (in the example above Databasestrategy), and then define the specific class (Mysqldbstrategy, Oracledbstrategy) that implements the interface. In these concrete classes, the implementation of specific logic. Finally, you define a class (Databasemanager) that manages the database connection, and there is a method within it that accepts the parameters of a specific class instance. We can see that this parameter is Databasestrategy type, that is to say, it can accept any instance of a class that implements the Databasestrategy interface (where the object substitution mechanism, polymorphism is used) to complete the processing of the database connection. If we still need to deal with another database such as SQL Server, we just need to create a Sqlserverdbstrategy class to implement the Databasestrategy interface, Pass an instance of the class to the Databasemanager process method.
Summary: Strategy mode is a way to define a series of algorithms. Conceptually, these algorithms do all the same work, but are implemented differently.