模板是行为设计模式之一,抽象类定义了一组执行其方法的方式/模板。
它的子类可以重写/实现这些方法,但调用方式与抽象类定义的方式相同
让我们通过一个例子来理解这一点:
关键概念
模板:定义算法的结构/方式/模板的抽象类
具体实现:模板的具体实现
客户端:将使用此模板的客户端
public abstract class gametemplate{ //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 gametemplate{ @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 gametemplate{ @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 gametemplate football = new football(); football.play();// play() will strictly follow the sequence of method execution defined in the final play() method gametemplate 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等所有设计原则
以上就是模板的详细内容,更多请关注抖狐科技其它相关文章!
-
小红书育婴博主怎么赚钱
小红书育婴博主可以通过8种变现途径:1. 广告推广;2. 直播带货;3. 知识付费;4. 电商变现;5. 训练营/社群运营;6. 培训讲座;7. 品牌咨询;8. 自媒体运营。小红书育婴博主如何变现 小...
-
一甜相机如何关掉延时拍摄
在使用一甜相机进行延时拍摄时,如果您希望关闭此功能,却不知道具体方法,那么本篇文章将为您详细解答。php小编苹果将分步指导您如何轻松关闭一甜相机的延时拍摄功能,帮助您快速解决困扰。请继续阅读以下内容,...
-
play商店老是闪退怎么办
要解决 google play 商店闪退问题,请按照以下步骤操作:确保设备已连接到稳定的网络。强制停止 play 商店并清除其数据。重新启动设备。更新 play 商店。卸载并重新安装 play 商店(...
-
为什么play的过去式是加ed
play的过去式是played,因为它是一个不规则动词,其过去式拼写和发音随着时间的推移发生了演变,从过去的"plaide"演变而来。为什么play的过去式是play-ed 对于许多英语动词来说,过去...
-
戏法门第二章怎么通关 戏法门第二章攻略
在《戏法门》这款冒险游戏中,玩家将踏上一段探索神秘关卡的旅程,从平凡走向超凡。第二章中,玩家将面临诸多悬疑谜题和机关挑战,需要运用智慧和勇气,解开层层谜团。为了帮助玩家顺利通关,php小编子墨为大家带...