Java設計模式之從[歡迎介面]分析模板方法(Template Method)模式
阿新 • • 發佈:2018-12-26
模板方法是在抽象類中最常用的模式了(應該沒有之一),它定義一個操作中演算法的骨架,而將一些步驟延遲到子類中,使得子類可以不改變一個演算法的結構即可重新定義演算法的某些步驟。
例如我們要編寫一個歡迎介面,如果使用者是第一次開啟本軟體,則彈出一個歡迎的提示。為了能夠實現複用,將這個機制當成一個基類,Java程式碼如下:
abstract class FirstLogin{ abstract protected void showIntro(); boolean firstLogin; public FirstLogin(boolean firstLogin){ this.firstLogin = firstLogin; } public void show(){ if (firstLogin){ showIntro(); } } } class HelloWorld extends FirstLogin{ public HelloWorld(boolean firstLogin) { super(firstLogin); } protected void showIntro(){ System.out.println("歡迎你第一次使用本程式! Hello world!"); } } public class TemplateMethod { public static void main(String[] args) { HelloWorld helloWorld1 = new HelloWorld(false); System.out.println("HelloWorld 1:"); helloWorld1.show(); HelloWorld helloWorld2 = new HelloWorld(true); System.out.println("HelloWorld 2:"); helloWorld2.show(); } }
FirstLogin中的show方法為模板方法。它用了showIntro這個抽象方法定義了出現歡迎介面的演算法,而它的子類將來實現showIntro方法。也就是說,基類用於實現不變的部分,而將可變的部分留給子類,是十分常見的一種模式。