Java之路:抽象类的应用——模板设计模式

模板设计模式是一种使用抽象类定义行为模板的模式,子类可以通过覆写抽象方法实现不同逻辑。例如,机器人、美女、帅哥有不同操作行为,如吃饭、工作、跑步和睡觉。通过抽象类,可以定义这些行为的通用流程,子类只需实现具体的行为差异。
摘要由CSDN通过智能技术生成

模板设计模式

在使用抽象类时,可以将部分逻辑以具体方法和具体构造函数的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现,这就是模板方法模式。

看下面这个例子:
现在有三类事物机器人、美女、帅哥,这三类事物可以完成的功能如下:

机器人:吃饭、工作;
美女:吃饭、跑步、睡觉;
帅哥:吃饭、工作、跑步、睡觉。

那么现在的问题就是如何将以上的程序变成操作类。
那么首先应该思考的是这三类事物的共同特征:四个固定的操作行为(吃饭、工作、跑步和睡觉)。

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程序设计上使用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值