模板是行為設計模式之一,抽象類別定義了一組執行其方法的方式/模板。
它的子類別可以重寫/實作這些方法,但呼叫方式與抽象類別定義的方式相同
讓我們透過一個例子來理解這一點:
關鍵概念
模板:定義演算法的結構/方式/模板的抽象類別
具體實作:模板的具體實作
客戶端:將使用此範本的客戶端
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中文網其他相關文章!

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版
中文版,非常好用

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)