抽象类-模板设计模式

package 抽象类_模板设计模式;

public class Test {
    public static void main(String[] args) {
       Person p=new Person();
       Robbt r=new Robbt();
       Pig pig=new Pig();
       p.command(Action.EAT);
       r.command(Action.EAT);
       pig.command(Action.EAT);
       p.command(Action.WORK);
       r.command(Action.WORK);
       pig.command(Action.WORK);
       p.command(Action.SLEEP);
       r.command(Action.SLEEP);
       pig.command(Action.SLEEP);
    }
}
/*
 * 抽象类:只定义了行为(抽象方法),
 *      eat()
 *      work()
 *      sleep()
 *      command()
 *      但没有具体实现,就相当于是给了一个模板类,规则就按照模板上的要求填写,具体怎么写看具体子类
 */
abstract class  Action {
    
     public static final  int EAT=1;
     public static final  int WORK=5;
     public static final  int SLEEP=10;
    public abstract void eat();
    public abstract void work();
    public abstract void sleep();
    //通过命令确定要执行什么任务,至于任务怎么实现,取决于子类对象
    public  void command(int command){
        switch(command){
          case  EAT:
              this.eat();
              break;
          case  WORK:
              this.work();
              break;
          case  SLEEP:
              this.sleep();
              break;
          case EAT+WORK+SLEEP:
              this.eat();
              this.sleep();
              this.work();
        }
   }
}

class Pig extends Action{
    @Override
    public void eat() {
       System.out.println("猪吃饲料");    
    }
    @Override
    public void work() {
      
    }
    @Override
    public void sleep() {
       System.out.println("猪睡在圈里");
    }    
}

class Robbt extends Action{
    @Override
    public void eat() {
       System.out.println("机器人需要吃饭");    
    }
    @Override
    public void work() {
      System.out.println("不停的工作");
    }
    @Override
    public void sleep() {
     
    }    
}
class Person extends Action{
    @Override
    public void eat() {
       System.out.println("人需要吃美食");    
    }
    @Override
    public void work() {
      System.out.println("更好努力的工作");
    }
    @Override
    public void sleep() {
       System.out.println("床上睡觉");
    }    
}

 

posted @ 2017-10-21 20:45  scwyfy  阅读(167)  评论(0编辑  收藏  举报