Java Design Patterns - Strategy Pattern practical application scenarios

Fault-tolerant recovery mechanism
        fault-tolerant recovery mechanism is very common in application development functions. So what is the fault-tolerant restore it? Simply put, it is this: when the program is run, under normal circumstances should be done in a certain way, if in some way to do an error occurs, the system does not collapse, nor can not continue to run this down, and It is the ability to tolerate mistakes, not only can tolerate running errors, it also provides an alternative after the error, which is the recovery mechanism to replace the function of the normal execution of the program continues to run down.
        For example the actual point of it, in such a system, all the operations should have a log, but also need to have the log management interface, in this case it will usually log in a database, to facilitate the subsequent management, but when logging into the database, an error may occur, for example, temporarily Rom database, and then the first record in the file inside, and then at the right time to record in the file and then transcribed into a database.
        For such design features, you can use the Strategy pattern, the log records to the database and log files as two recording log to the policy, and then dynamically switch as needed during operation.
        In the implementation of this example, the context model to be a policy to select a specific algorithm, the selection is a good example of the foregoing specific algorithm by the client, and then provided to the context.
        The following example is to look through the code.
(1) logging policy to define the interface, very simple, is a method of logging, the following sample code:

/**

 * Logging policy interface

 */

public interface LogStrategy {

    /**

     * Logging

     * @Param msg log information to be recorded

     */

    public void log(String msg);

}
 


(2) implement log policy interface to implement the default database implementation, assuming that if the log length exceeds the length is wrong, manufacturing errors is one of the most common runtime errors, sample code as follows:

/**

 * Logging to database

 */

public class DbLog implements LogStrategy{

    public void log(String msg) {     

       // manufacturing error

       if(msg!=null && msg.trim().length()>5){

           int a = 5/0;

       }

       System.out.println ( "Now the '" + msg + "' record to the database");

    }

}
 

Next to achieve log file to, the following sample code:

/**

 * Logging to file

 */

public class FileLog implements LogStrategy{

    public void log(String msg) {

       System.out.println ( "Now the '" + msg + "' to a file");

    }

}
 

(3) Next, define the context in which such strategies, this is noted that selection of a particular strategy algorithm implemented in the context of which, the client is not required to specify a specific strategy algorithm, the following sample code:

 

(4) Now look at the client, not the work of selecting a specific implementation strategy algorithm becomes very simple, deliberately calling more than once, you can see different effects, sample code as follows:

 

 (5) summary of what, by the example above, you will see a simple application strategy mode, but also the way to look at the design and realization of fundamental fault-tolerant recovery mechanism. In practical applications, the need to design fault-tolerant recovery system general requirements are high, the application will be more complicated, but the basic idea is the same.

 Author demonstrates a variant strategy.

This example also illustrates another important design concept, the principle of single responsibility.

Single Responsibility Principle (SRP), it should be only one reason in terms of a class changes caused by it.

If a class too many responsibilities to bear, it means these functions coupled together, a change in responsibilities may weaken or inhibit the ability of the class to complete other duties, this coupling will lead to fragile design

当变化发生时,设计会遭受到意想不到的破坏。

容错恢复机制
        容错恢复机制是应用程序开发中非常常见的功能。那么什么是容错恢复呢?简单点说就是:程序运行的时候,正常情况下应该按照某种方式来做,如果按照某种方式来做发生错误的话,系统并不会崩溃,也不会就此不能继续向下运行了,而是有容忍出错的能力,不但能容忍程序运行出现错误,还提供出现错误后的备用方案,也就是恢复机制,来代替正常执行的功能,使程序继续向下运行。
        举个实际点的例子吧,比如在一个系统中,所有对系统的操作都要有日志记录,而且这个日志还需要有管理界面,这种情况下通常会把日志记录在数据库里面,方便后续的管理,但是在记录日志到数据库的时候,可能会发生错误,比如暂时连不上数据库了,那就先记录在文件里面,然后在合适的时候把文件中的记录再转录到数据库中。
        对于这样的功能的设计,就可以采用策略模式,把日志记录到数据库和日志记录到文件当作两种记录日志的策略,然后在运行期间根据需要进行动态的切换。
        在这个例子的实现中,要示范由上下文来选择具体的策略算法,前面的例子都是由客户端选择好具体的算法,然后设置到上下文中。
        下面还是通过代码来示例一下。
(1)先定义日志策略接口,很简单,就是一个记录日志的方法,示例代码如下:

/**

 * 日志记录策略的接口

 */

public interface LogStrategy {

    /**

     * 记录日志

     * @param msg 需记录的日志信息

     */

    public void log(String msg);

}
 


(2)实现日志策略接口,先实现默认的数据库实现,假设如果日志的长度超过长度就出错,制造错误的是一个最常见的运行期错误,示例代码如下:

/**

 * 把日志记录到数据库

 */

public class DbLog implements LogStrategy{

    public void log(String msg) {     

       //制造错误

       if(msg!=null && msg.trim().length()>5){

           int a = 5/0;

       }

       System.out.println("现在把 '"+msg+"' 记录到数据库中");

    }

}
 

接下来实现记录日志到文件中去,示例代码如下:

/**

 * 把日志记录到文件

 */

public class FileLog implements LogStrategy{

    public void log(String msg) {

       System.out.println("现在把 '"+msg+"' 记录到文件中");

    }

}
 

(3)接下来定义使用这些策略的上下文,注意这次是在上下文里面实现具体策略算法的选择,所以不需要客户端来指定具体的策略算法了,示例代码如下:

 

(4)看看现在的客户端,没有了选择具体实现策略算法的工作,变得非常简单,故意多调用一次,可以看出不同的效果,示例代码如下:

 

 (5)小结一下,通过上面的示例,会看到策略模式的一种简单应用,也顺便了解一下基本的容错恢复机制的设计和实现。在实际的应用中,需要设计容错恢复的系统一般要求都比较高,应用也会比较复杂,但是基本的思路是差不多的。

 作者演示了策略的一种变体。

这个例子同时说明了设计中的另外一个重要的概念,单一职责原理。

单一职责原则(SRP),就一个类而言应该仅有一个引起它变化的原因。

如果一个类承担的职责过多,就等于把这些职责耦合在一起,一个职责的变化可能会削弱或者抑制这个类完成其他职责的能力,这种耦合会导致脆弱的设计

当变化发生时,设计会遭受到意想不到的破坏。

Guess you like

Origin www.cnblogs.com/LoveShare/p/10953940.html