您的位置:首页 > 其它

策略模式

2015-12-08 00:28 218 查看
一 日志接口:

/**
* 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: