CarModel为抽象类,将所有的车都抽象出启动,停止,鸣笛和运行四个方法,汽车运行时要启动,可能会鸣笛,结束要停止,所以抽象中调用三个方法,AcarModel和BCarModel为具体的某中品牌的车,具体代码如下:
抽象类CarModel:
public abstract class CarModel{
protected abstract void start();
protected abstract void stop();
protected abstract void alarm();
final public void run(){
this.start();
if(this.isAlarm()){
this.alarm();
}
this.stop();
}
protected boolean isAlarm(){
return true;
}
}
模板类ACarModel:
public abstract class ACarModel extends CarModel{
private boolean alarmFlag = true;//默认鸣笛
protected abstract void start(){
system.out.println("A车启动");
}
protected abstract void stop(){
system.out.println("A车停止");
}
protected abstract void alarm(){
system.out.println("A车鸣笛扰民");
}
protected boolean isAlarm(){
return this.alarmFlag;
}
//可设置是否鸣笛
public void setAlarm(boolean isAlarm){
this.alarmFlag = isAlarm;
}
}
模板类BCarModel:
public abstract class BCarModel extends CarModel{
protected abstract void start(){
system.out.println("B车启动");
}
protected abstract void stop(){
system.out.println("B车停止");
}
protected abstract void alarm(){
system.out.println("B车鸣笛也扰民");
}
//默认不鸣笛
protected boolean isAlarm(){
return false;
}
}
调用类Client:
public class Client{
public static void main(String[] args) throws IOExecption{
ACarModelaCar = new ACarModel();
aCar.run();//运行会鸣笛
aCar.setAlarm(false);
aCar.run();//运行不会鸣笛
BCarModelbCar = new BCarModel();
bCar.run();//运行不会鸣笛
}
}
多个对象抽象出共同的方法,最后由一个方法全部调用这些方法,是否鸣笛为A、B存在差异的地方,可通过添加作为判断条件的方法进行控制。