静态代理和装饰模式的区别

截取一篇文章里的总结:代理模式主要是控制对某个特定对象访问,而装饰模式主要是为了给对象添加行为

代理模式:

定义一个测试接口,里面定义一个测试用例执行方法

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值