题目要求:
应用程序开发中常见的功能:
程序运行的时候,正常情况下应该按某种方式来做,如果按照某种方式来做发生错误的话,系统并不会崩溃,而是继续运行,能提供出错后的备用方案。
日志记录的例子:把日志记录到数据库和日志记录到文件当做两种记录日志的策略。
UML图:
代码:
//日志上下文(环境类)
//包含一个抽象策略类
//当出现意外时:启动备用方案
public class LogContext {
public void log(String msg) throws Exception
{
LogStrategy strategy=new DbLog();
try{
strategy.log(msg);
}catch(Exception err){
strategy=new FileLog();
strategy.log(msg);
}
}
}
//日志策略类接口
//定义其子类的共有方法
public interface LogStrategy {
public void log(String msg) throws Exception;
}
//策略1,正常情况下选取该策略
//但该策略可能不中用、不中用就抛出异常,让环境类决定补救策略选谁
public class DbLog implements LogStrategy {
public void log(String msg) throws Exception {
if(msg!=null &&msg.trim().length()>5){
throw new Exception("有异常");
}
System.out.println("现在把'"+msg+"'记录到数据库中");
}
}
//策略类
//在本例中——备胎1号
public class FileLog implements LogStrategy {
public void log(String msg) {
System.out.println("现在把'"+msg+"'记录到文件中");
}
}
测试代码:
public class Main {
public static void main(String[] args) throws Exception {
LogContext log=new LogContext();
log.log("记录日志");
log.log("再次记录日志"); //长度超过5
}
}
测试结果: