模板方法(Template Method DP):在一個(gè)方法中定義一個(gè)算法的骨架叠国,而將一些步驟延遲到子類中屯远。子類可以在不改變算法結(jié)構(gòu)的前提下金麸,重新定義算法的某些步驟。
模板方法的實(shí)現(xiàn)是通過鉤子(Hooks)套鹅。什么是鉤子呢?
鉤子是一種被聲明在超類中的方法汰具,只有空的或者默認(rèn)的實(shí)現(xiàn)卓鹿,其存在的意義就是讓子類改寫的。
我想到的最典型的例子:安卓開發(fā)的Activity留荔,各種onCreate,onResume,onDestroy方法都是鉤子吟孙,子類可以很方便地加入自己的東西,因此Activity很明顯采用了模板方法聚蝶。
什么是模板杰妓?超類的算法或者實(shí)現(xiàn)就是模板。實(shí)際生活當(dāng)中我們也用過模板碘勉,模板就是拿過來(lái)改改用的巷挥。全部照抄不叫模板,全部推翻也不叫模板验靡。
這里又可以和策略模式還有工廠方法比較一下倍宾。從概念上來(lái)講其實(shí)差別很明顯雏节,策略模式是對(duì)同一方法的不同實(shí)現(xiàn)的封裝,模板是子類來(lái)決定如何實(shí)現(xiàn)一個(gè)算法或者流程高职,工廠方法是子類決定實(shí)例化具體類矾屯。
代碼:
行竊方法,是一個(gè)模板初厚,留下3個(gè)鉤子函數(shù)件蚕,分別是挑目標(biāo),迷惑目標(biāo)产禾,偷得物品:
/**
*
* StealingMethod defines skeleton for the algorithm.
*
*/
public abstract class StealingMethod {
private static final Logger LOGGER = LoggerFactory.getLogger(StealingMethod.class);
protected abstract String pickTarget();
protected abstract void confuseTarget(String target);
protected abstract void stealTheItem(String target);
/**
* Steal
*/
public void steal() {
String target = pickTarget();
LOGGER.info("The target has been chosen as {}.", target);
confuseTarget(target);
stealTheItem(target);
}
}
選擇老弱的哥布林女性排作,Hit&Run方法,搶了就跑:
/**
*
* HitAndRunMethod implementation of {@link StealingMethod}.
*
*/
public class HitAndRunMethod extends StealingMethod {
private static final Logger LOGGER = LoggerFactory.getLogger(HitAndRunMethod.class);
@Override
protected String pickTarget() {
return "old goblin woman";
}
@Override
protected void confuseTarget(String target) {
LOGGER.info("Approach the {} from behind.", target);
}
@Override
protected void stealTheItem(String target) {
LOGGER.info("Grab the handbag and run away fast!");
}
}
選擇小商人亚情,哭著跑向目標(biāo)妄痪,擁抱然后掏包:
/**
*
* SubtleMethod implementation of {@link StealingMethod}.
*
*/
public class SubtleMethod extends StealingMethod {
private static final Logger LOGGER = LoggerFactory.getLogger(SubtleMethod.class);
@Override
protected String pickTarget() {
return "shop keeper";
}
@Override
protected void confuseTarget(String target) {
LOGGER.info("Approach the {} with tears running and hug him!", target);
}
@Override
protected void stealTheItem(String target) {
LOGGER.info("While in close contact grab the {}'s wallet.", target);
}
}
半成年人盜賊,使用行竊方法模板來(lái)偷東西:
/**
*
* Halfling thief uses {@link StealingMethod} to steal.
*
*/
public class HalflingThief {
private StealingMethod method;
public HalflingThief(StealingMethod method) {
this.method = method;
}
public void steal() {
method.steal();
}
public void changeMethod(StealingMethod method) {
this.method = method;
}
}
測(cè)試:
public static void main(String[] args) {
HalflingThief thief = new HalflingThief(new HitAndRunMethod());
thief.steal();
thief.changeMethod(new SubtleMethod());
thief.steal();
}
其實(shí)這里也使用了策略模式楞件,所以可以實(shí)時(shí)切換衫生。模板方法本身是不帶這個(gè)功能的。