策略模式——写日志

本文探讨了如何运用策略模式来灵活地处理日志记录,包括选择不同的日志策略,如文件日志、数据库日志和云日志等。通过实例展示了如何创建和切换日志策略,以适应不同场景的需求。
摘要由CSDN通过智能技术生成

 

//日志策略接口
public interface LogStrategy {
	public void log(String msg) throws FileNotFoundException, Exception;
}
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{
	@Override
		public void log(String msg) throws Exception {
		File a=new File("E:\\日志.txt");
		a.createNewFile();
		FileWriter writer = new FileWriter(a , true);
		BufferedWriter out = new BufferedWriter(writer);  
		out.write(msg);
		out.flush(); 
		out.close(); 
        	System.out.println("已经把" + msg + "记录导入日志文档");
		}
}
public class LogContext {
	public void log(String msg) throws Exception {
		LogStrategy strategy = new DbLog();
            //下面的try—catch借用前面写入数据库时的异常操作,实现了实际类似于if-else的操作
            //这样就省去现在try中if-else判断,提高了效率
	    try
	    {
	        strategy.log(msg);
	    }catch(Exception e)
	    {
	        strategy=new FileLog();
	        	strategy.log(msg);
	    }
	}
}
public class Client {
	public static Scanner sc=new Scanner(System.in);
	public static void main(String[] args) throws Exception {
		LogContext log = new LogContext();
		String a,b;
		a=sc.next();
		b=sc.next();
        log.log(a);
        log.log(b);
        sc.close();
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值