模板设计模式
在使用抽象类时,可以将部分逻辑以具体方法和具体构造函数的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现,这就是模板方法模式。
看下面这个例子:
现在有三类事物机器人、美女、帅哥,这三类事物可以完成的功能如下:
机器人:吃饭、工作;
美女:吃饭、跑步、睡觉;
帅哥:吃饭、工作、跑步、睡觉。
那么现在的问题就是如何将以上的程序变成操作类。
那么首先应该思考的是这三类事物的共同特征:四个固定的操作行为(吃饭、工作、跑步和睡觉)。
abstract class Action { // 表示操作行为
public static final int EAT = 1; // 吃
public static final int WORK = 2; // 工作
public static final int SLEEP = 5; // 睡
public static final int RUN = 10; // 跑步
public abstract void eat(); // 声明一些抽象方法
public abstract void work();
public abstract void sleep();
public abstract void run();
public void command(int i) { // 具体的方法
switch(i) {
case EAT : this.eat(); break; // 1
case WORK : this.work(); break; // 2
case SLEEP : this.sleep(); break; // 5
case RUN : this.run(); break; // 10
case EAT + WORK : // 3
this.eat();
this.work();
break;
case EAT + SLEEP + RUN : // 16
this.eat();
this.sleep();
this.run();
break;
case EAT + SLEEP + RUN + WORK : // 18
this.eat();
this.sleep();
this.run();
this.work();
break;
}
}
}
class Robot extends Action { // 定义子类机器人的行为
@Override
public void eat() { // 重写抽象方法
System.out.println("为机器人加燃料。");
}
public void sleep() {}
public void run() {}
public void work() {
System.out.println("让机器人开始工作。");
}
}
class Woman extends Action { // 定义子类Woman的行为
public void eat() { // 重写抽象方法
System.out.println("请美女吃饭。");
}
public void sleep() {
System.out.println("让美女睡美容觉。");
}
public void run() {
System.out.println("让美女跑步健身");
}
public void work() {}
}
class Man extends Action { // 定义子类Man的行为
public void eat() { // 重写抽象方法
System.out.println("帅哥吃早饭、午饭、晚饭、加餐。");
}
public void sleep() {
System.out.println("帅哥休息好以恢复精神和体力。");
}
public void run() {
System.out.println("帅哥通过跑步来锻炼身体。");
}
public void work() {
System.out.println("帅哥为了和美女幸福地生活在一起,要好好工作。");
}
}
public class TemplateMethod {
public static void main(String[] args) {
Action actA = new Robot(); // 机器人行为
actA.command(Action.EAT);
actA.command(Action.WORK);
Action actB = new Woman(); // 美女行为
actB.command(Action.EAT + Action.SLEEP + Action.RUN);
Action actC = new Man(); // 帅哥行为
actC.command(Action.EAT + Action.SLEEP + Action.RUN + Action.WORK);
}
}
【结果】
此时,如果要想实现指定的操作,只需要将方法按照要求覆写即可,相当于父类定义出了一个操作模板。实际用的时候也可以在Servlet程序设计上使用。