//日志策略接口
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();
}
}