首頁 > Java > java教程 > 範本

範本

Linda Hamilton
發布: 2024-09-22 22:16:02
原創
649 人瀏覽過

範本

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

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

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

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

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板