設計模式之模板模式

        模板模式,字面意思針對的是在應用開發中流程固定,具有固定模板的解決方法。

        舉例,在應用中流程分爲before、onbusiness、end三個步驟,其中,before和end是固定不變的,而onBusiness根據具體的用戶不同而不同。這個時候,就應用模板模式。代碼如下:

       模板的代碼爲:

package com.designpattern.template;

abstract public class Template{

    public void template(){

        before();
        onBusiness();
        end();
    }

    public void before(){
        System.out.println("before");
    }

    abstract public void onBusiness();

    public void end(){
        System.out.println("end");
    }
}

 其他的需要這個模板的可以繼承這個模板類,並添加具體的onBussiness方法。代碼如下:

package com.designpattern.template;

public class ActualExecutor extends Template{


    @Override
    public void onBusiness(){
        System.out.println("on business.");
    }

}

 這樣,ActualExecutor類繼承了Template類中的before和end方法。

測試代碼如下:

package com.designpattern.template;

import org.junit.Test;

public class TemplateTest{

    @Test
    public void testTemplate(){

        ActualExecutor actualExecutor = new ActualExecutor();
        actualExecutor.template();
    }
}

 結果爲:

before
on business.
end

Process finished with exit code 0

 簡單實現了模板模式。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章