文章目录
一、什么是代理模式?
代理模式的定义。
为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。对象实现同一个接口,先访问代理类再访问真正要访问的对象。
代理模式分为静态代理、动态代理。
静态代理是由程序员创建或工具生成代理类的源码,再编译代理类。所谓静态也就是在程序运行前就已经存在代理类的字节码文件,代理类和委托类的关系在运行前就确定了。
动态代理是在实现阶段不用关心代理类,而在运行阶段才指定哪一个对象。
二、实现代码
1.接口实现(Add,Sub,Mul,Div)
代码如下(其他实现类似):
public class Add implements CalcUnit {
@Override
public boolean fit(String operator) {
return operator.equals("+");
}
@Override
public double calc(double x, double y) {
return x + y;
}
public String toString() {
return "+";
}
}
2.接口(CalcUnit)
代码如下:
public interface CalcUnit {
boolean fit(String operator);
double calc(double x,double y);
}
3.代理类(Proxy)
代码如下:
import java.io.PrintWriter;
import java.util.GregorianCalendar;
public class CalcUnitProxy implements CalcUnit {
CalcUnit cu;
PrintWriter pw;
public void setLogWriter(PrintWriter pw) {
this.pw=pw;
}
public void setCalcUnit(CalcUnit cu) {
this.cu = cu;
}
public boolean fit(String operator) {
String s =cu.toString();
if(s.equals(operator))
{
pw.println("["+GregorianCalendar.getInstance().getTime()+"]判断操作符"+s+"是否符合当前计算单元:ture");
}else{
pw.println("["+GregorianCalendar.getInstance().getTime()+"]判断操作符"+s+"是否符合当前计算单元:false");
}
return cu.fit(operator);
}
public double calc(double x, double y) {
String s =cu.toString();
pw.println("["+GregorianCalendar.getInstance().getTime()+"]计算"+x+s+y+"的结果为:"+cu.calc(x, y));
return cu.calc(x, y);
}
}
4.Main(包括日志文件写入)
代码如下:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
CalcUnit[] calculator = {new Add(),new Sub(),new Mul(),new Div()};
Scanner input = new Scanner(System.in);
CalcUnitProxy proxy = new CalcUnitProxy();
PrintWriter pw = null;
try {
pw = new PrintWriter(new File("D:/log.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
proxy.setLogWriter(pw);
while(true)
{
System.out.print("输入:");
String line = input.nextLine();
if(line.equals("exit"))
break;
String[] items = line.trim().split(" ");
if(items.length != 3)
continue;
String operator = items[1];
double x = Double.parseDouble(items[0]);
double y = Double.parseDouble(items[2]);
// 代理对象替代具体计算单元进行判断和计算
for(CalcUnit cu : calculator) {
proxy.setCalcUnit(cu);
if(proxy.fit(operator)) {
System.out.printf("结果%4.2f\n", proxy.calc(x, y));
break;
}
}
pw.flush();
}pw.close();
input.close();
}
}
三、类图
四、日志文件
总结
本次实践主要针对代理模式的应用以及对日志文件的初步理解和写入,类图采用starUML绘制,代码采用eclipse进行编译,实现了一个简单计算器,采用java.util.GregorianCalendar类,指定的时区和默认语言环境获取日历,返回Calendar的基于给定时区中的当前时间。最后采用printwriter生成对应的日志文件。