這篇文章主要介紹java模板模式的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
模板模式,顧名思義,就是通過模板拓印的方式。
定義模板,就是定義框架、結構、原型。定義一個我們共同遵守的約定。
定義模板,我們的剩余工作就是對其進行充實、豐潤,完善它的不足之處。
定義模板采用抽象類來定義,公共的結構化邏輯需要在抽象類中完成,只將非公共的部分邏輯抽象成抽象方法,留待子類充實實現。
下面首先通過一個簡單的程序來分析一下,例如:現在有三種類型:豬、機器人、人;
豬具備三種功能:吃、睡、跑
機器人又兩個功能:吃、工作
人具備四個功能:吃、睡、跑、工作。
現在就要求設計一個程序,可以讓這三類不同的類型,進行工作?,F在給出的三個類實際上并沒有任何聯系
UML圖:
源代碼:
abstract class Action{ public static final int EAT = 1; public static final int SLEEP = 5; public static final int RUN = 20; public static final int WORK = 30; public abstract void eat(); public abstract void sleep(); public abstract void run(); public abstract void work(); public void order(int flag){ switch(flag){ case EAT: this.eat(); break; case SLEEP: this.sleep(); break; case RUN: this.run(); break; case WORK: this.work(); break; case EAT+WORK: this.eat(); this.work(); break; case EAT+WORK+RUN+SLEEP: this.eat(); this.sleep(); this.run(); this.work(); break; case EAT+RUN+SLEEP: this.eat(); this.sleep(); this.run(); break; } } } class Person extends Action{ public void eat(){ System.out.print("人吃,"); } public void sleep(){ System.out.print("人睡,"); } public void run(){ System.out.print("人跑,"); } public void work(){ System.out.print("人工作,"); } } class Pig extends Action{ public void eat(){ System.out.print("豬吃,"); } public void sleep(){ System.out.print("豬睡,"); } public void run(){ System.out.print("豬跑,"); } public void work(){} } class Robet extends Action{ public void eat(){ System.out.print("機器人吃,"); } public void sleep(){} public void run(){} public void work(){ System.out.print("機器人工作,"); } } public class MoBan{ public static void main(String args[]){ /* 人吃,人睡,人跑,人工作, 豬吃,豬睡,豬跑, 機器人吃,機器人工作, */ Action ren = new Person(); ren.order(Action.EAT+Action.SLEEP+Action.RUN+Action.WORK); System.out.println(); Action pig = new Pig(); pig.order(Action.EAT+Action.SLEEP+Action.RUN); System.out.println(); Action robet = new Robet(); robet.order(Action.EAT+Action.WORK); } }
實際上通過此程序的定義結構你可以清楚的發現一個問題:
抽象類在實際的使用過程之中會定義一些固化的模式,它只能接受幾種特定的指令;但是每種指定的具體實現由子類負責完成,我們父類只是做了方法的約定。
以上是“java模板模式的示例分析”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。