首頁  >  文章  >  Java  >  範本

範本

Linda Hamilton
Linda Hamilton原創
2024-09-22 22:16:02604瀏覽

範本

模板是行為設計模式之一,抽象類別定義了一組執行其方法的方式/模板。

它的子類別可以重寫/實作這些方法,但呼叫方式與抽象類別定義的方式相同

讓我們透過一個例子來理解這一點:

關鍵概念
模板:定義演算法的結構/方式/模板的抽象類別
具體實作:模板的具體實作
客戶端:將使用此範本的客戶端

public abstract class Game範本{
    //these below methods can be overridden based on the type of game
    public abstract void initialize();
    public abstract void startPlay();
    public abstract void  endPlay();

    //All the subclasses must use this same method to play the game i.e. following the same template present in this method,
    //Hence it is declared as final.
    public final void play(){
        initialize();
        startPlay();
        endPlay();
    }
}

public class Cricket extends Game範本{


    @Override
    public void initialize(){
        System.out.println("Cricket has been initialized");
    }
    @Override
    public void startPlay(){
        System.out.println("Cricket game has been started");
    }
    @Override
    public void endPlay(){
        System.out.println("Cricket game has ended");
    }

}

public class Football extends Game範本{

    @Override
    public void initialize(){
        System.out.println("Football has been initialized");
    }
    @Override
    public void startPlay(){
        System.out.println("Football game has been started");
    }
    @Override
    public void endPlay(){
        System.out.println("Football game has ended");
    }

}

public class Main{
    public static void main(String args[]){

        //Create a football game object 
        Game範本 football = new Football();
        football.play();// play() will strictly follow the sequence of method execution defined in the final play() method

        Game範本 cricket = new Cricket();
        cricket.play();
    }
}

輸出:

Football has been initialized
Football game has been started
Football game has ended
Cricket has been initialized
Cricket game has been started
Cricket game has ended

注意:程式碼遵循LSP、ISP、SRP、OCP等所有設計原則

以上是範本的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:代理人下一篇:代理人