截取一篇文章里的总结:代理模式主要是控制对某个特定对象访问,而装饰模式主要是为了给对象添加行为
代理模式:
定义一个测试接口,里面定义一个测试用例执行方法
interface ITest{
void execute();
}
定义一个测试用例类,具体实现测试执行函数
class TestCase implements ITest{
public void execute(){
System.out.println("running testcase");
}
}
定一个测试者类,因为测试用例本身不能去执行当然要人去执行,所以认为测试者是代理测试用例执行的代理类,同样实现具体execute方法,但是里面加了一些逻辑,只有叫xiaoming的测试者才能执行测试用例。
class Tester implements ITest{
private ITest test;
private String testerName;
Tester(ITest test,String testerName){
this.test = test;
this.testerName = testerName;
}
public void execute(){
if(testerName == "xiaoming"){
System.out.println("I am xiaoming. I have permission to execute test.");
test.execute();
} else{
System.out.println("Sorry, only xiaoming has permission to execute test.");
}
}
}
主程序
public class MyProxy {
public static void main(String[] argv){
ITest test = new TestCase();
ITest tester1 = new Tester(test,"xiaoming");
tester1.execute();
ITest tester2 = new Tester(test,"xiaoxu");
tester2.execute();
}
测试结果:
I am xiaoming. I have permission to execute test.
running testcase
Sorry, only xiaoming has permission to execute test.
}
装饰模式:
同样定义测试接口
interface ITest{
void execute();
}
同样定义一个测试用例类
class TestCase implements ITest{
public void execute(){
System.out.println("running testcase");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
定义一个时间装饰类,打印测试用例执行的开始时间和结束时间
class TimeDecorator{
private ITest test;
TimeDecorator(ITest test){
this.test = test;
}
public void execute(){
Date date = new Date();
System.out.println("Case start time:" + date.toString());
test.execute();
date = new Date();
System.out.println("Case end time:" + date.toString());
}
}
测试:
public class MyDecorator {
public static void main(String[] args) {
ITest testcase = new TestCase();
TimeDecorator td = new TimeDecorator(testcase);
td.execute();
}
}
结果:
Case start time:Tue May 22 22:35:05 CST 2018
running testcase
Case end time:Tue May 22 22:35:07 CST 2018