Fork me on GitHub

简述

例如,现在有三类事物:
机器人:充电,工作;
人:吃饭、工作、睡觉
猪:吃饭、睡觉
要求可以实现以上的操作控制,即可以控制人、机器人、猪的操作行为(吃、睡觉、工作)

定义一个行为类

abstract class Action {
	public static final int EAT = 1;
	public static final int SLEEP = 5;
	public static final int WORK = 7;
	public void command(int flag){
		// switch只支持数值判断,if支持条件判断
		switch(flag){
			case EAT:
				this.eat();
				break;
			case SLEEP:
				this.sleep();
				break;
			case WORK:
				this.work();
				break;
			case EAT + SLEEP:
				this.eat();
				this.sleep();
				break;
		}
	}
	// 因为现在不确定子类的实现是什么样的
	public abstract void eat();
	public abstract void sleep();
	public abstract void work();

}

定义机器人的类

class Rebot extends Action{
	public void eat(){
		System.out.println("机器人下在补充能量");
	}
	public void work(){
		System.out.println("机器人下在努力工作");
	}
	public void sleep() {}
}

定义人这个类

class Human extends Action{
	public void eat(){
		System.out.println("人正在吃饭");
	}
	public void sleep(){
		System.out.println("人正在睡觉");
	}
	public void work(){
		System.out.println("人正在为梦想努力奋斗");
	}
}

定义猪这个类

class Pig extends Action{
	public void eat(){
		System.out.println("猪正在吃饲料");
	}
	public void sleep(){
		System.out.println("猪下在长肉");
	}
	public void work(){}
}

调用测试

public class testDemo{
	public static void main(String args[]){
		func(new Rebot());
		func(new Human());
		func(new Pig());
	}
	public static void func(Action act){
		act.command(Action.EAT);	
		act.command(Action.SLEEP);	
		act.command(Action.WORK);	
	}
}

总结

1.如果真的要使用类继承,那么就使用抽象类(20%的情况)
2.抽象类强制规定了子类必须要做的事情,而且可以与抽象类的普通方法想配合
3.不管抽象类如何努力都有一个天生最大的问题:单继承局限

posted on 2019-11-30 15:34  anyux  阅读(210)  评论(0编辑  收藏  举报