程序运行的时候,正常情况下应该按某种方式来做,如果按照某种方式来做发生错误的话,系统并不会崩溃,而是继续运行,能提供出错后的备用方案。
把日志记录到数据库和日志记录到文件当做两种记录日志的策略
日志记录的策略接口:
package com.cmc; public interface LogStrategy { public void SaveLog(String msg); }
package com.cmc; public class FileLog implements LogStrategy { public void SaveLog(String msg) { // TODO Auto-generated method stub System.out.println("现在把"+msg+"日志记录到文件中..."); } }
package com.cmc; public class DataBaseLog implements LogStrategy { public void SaveLog(String msg) { // TODO Auto-generated method stub if(msg!=null&&msg.length()<6) System.out.println("现在把"+msg+"日志记录到数据库中..."); else { int a = 5/0;//制造错误,以便实现,如果在日志记录在数据库的过程中发生错误时,还能调用日志写到文件的策略 } } }日志上下文,包含一个策略对象,实现了对错误的处理
package com.cmc; public class LogContext { LogStrategy log = null; public void saveLog(String msg){ try{ log = new DataBaseLog(); log.SaveLog(msg); } catch(Exception e){ log = new FileLog(); log.SaveLog(msg); } } }
package com.cmc; public class Client { public static void main(String[] args){ LogContext log = new LogContext(); log.saveLog("LogMe"); log.saveLog("AndLogMeAgain"); } }
原文地址:http://blog.csdn.net/u014293306/article/details/46277385