策略模式
2015-12-08 00:28
218 查看
一 日志接口:
二 数据库日志实现:
三 文件日志实现:
四 策略逻辑:
五 客户端调用:
六 执行代码结果:
记录到数据库里的信息是:yaokj
记录到文件里的信息为:用户名为:yaokj
/** * Created by yaokj on 15-12-7. */ public interface Log { public String log(String msg) throws Exception; }
二 数据库日志实现:
/** * Created by yaokj on 15-12-7. */ public class DbLog implements Log { @Override public String log(String msg) throws Exception { //制造异常,虽然无聊,但是只是为了测试 if(msg.length() > 5){ throw new Exception("信息长度过长。"); } System.out.println("记录到数据库里的信息是:"+msg); return msg; } }
三 文件日志实现:
/** * Created by yaokj on 15-12-7. */ public class FileLog implements Log { @Override public String log(String msg) { System.out.println("记录到文件里的信息为:"+msg); return msg; } }
四 策略逻辑:
/** * Created by yaokj on 15-12-7. */ public class StrategyContext { public void log(String msg) throws Exception{ Log log = new DbLog(); try{ log.log(msg); }catch (Exception e){ log = new FileLog(); log.log(msg); } } }
五 客户端调用:
/** * Created by yaokj on 15-12-7. */ public class Client { public static void main(String[] args) throws Exception { StrategyContext context = new StrategyContext(); context.log("yaokj"); context.log("用户名为:yaokj"); } }
六 执行代码结果:
记录到数据库里的信息是:yaokj
记录到文件里的信息为:用户名为:yaokj
相关文章推荐
- 安卓开发中JDK、SDK、NDK、ADT、ANT等概念作用解释
- Spherical Harmonics Lighting
- MyEclipse安装插件出现“resolving and validating the profile”卡死问题的解决方案
- 数据结构线性表
- LAMP 1.9域名301跳转
- 回调函数实现冒泡法的多种排序
- php将文件夹打包成zip文件
- hdoj 5592 ZYB's Biology 【线段树】 hdoj 5590 ZYB's Biology 【字符串水题】
- c语言:按如下方式输出You are handsome!,每到下一行,就替换掉两边上的字符
- 微信开发
- UVA-12186 Another Crisis
- char[] char* string 的关系
- c语言:C语言清空输入缓冲区在标准输入(stdin)情况下的使用
- HDU 5489(2015 Asia Regional Hefei Online F )
- PHP 静态变量的使用
- 磁盘管理
- Content Delivery Network
- C语言程序设计整理(2)
- UVA-1220 Party at Hali-Bula
- Memcached 笔记与总结(9)Memcached 与 Session