抽象类的应用(模板设计)

例如现在有三类事物:

1.机器人  :充电,工作,

2.人        :吃饭,睡觉,工作

3.猪      :吃饭,睡觉

要求可以任意控制人,机器人,猪的操作行为.

 父类:定义一个行为类

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(flag){
            case EAT:
                this.eat() ;
                break ;
            case SLEEP:
                this.sleep() ; 
                break;
            case WORK :
                this.work() ;
                break;
            case EAT+WORK:
                this.eat() ;
                this.work() ;
                break ;
        }
        
    }
    public abstract void eat() ;
    public abstract void sleep() ;
    public abstract void work() ;
}
class Robot extends Action{
    public void eat() {
        System.out.println("Robot is charging") ;
    } 
    public void work(){
        System.out.println("Robot is working") ;
    }
    public void sleep(){}
    
}
class Human extends Action{
    public void eat(){
        System.out.println("man is eating") ;
    }
    public void work(){
        System.out.println("man is working") ;
    }
    public void sleep(){
        System.out.println("man is sleeping ") ;
    }
}
class Pig extends Action{
    public void eat(){
        System.out.println("Pig is eating") ; 
    }
    public void work(){
      
    }
    public void sleep(){
        System.out.println("Pig is sleeping ") ;
    }
}
public class Chouxianglei{
    public static void main(String arg[]){
        fun(new Robot()) ;
    }
    public static void fun(Action act){
        act.command(1) ;
        act.command(5) ;
    }
}

总结:

如果真的要使用类继承就使用抽象类

抽象类强制规定了子类必须要做的事情,而且可以与抽象类的普通方法配合。

不管抽象类如何努力都有一个天生最大的问题:::单继承局限。

原文地址:https://www.cnblogs.com/da-peng/p/5124135.html