1. 程式人生 > >靜態代理和裝飾模式的區別

靜態代理和裝飾模式的區別

擷取一篇文章裡的總結:代理模式主要是控制對某個特定物件訪問,而裝飾模式主要是為了給物件新增行為

代理模式:

定義一個測試介面,裡面定義一個測試用例執行方法

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