抽象类应用——模板设计模式

抽象类最主要的特点相当于制约了子类必须覆写的方法,同时抽象类中也可以定义普通方法,而且最为关键的是,这些普通方法定义在抽象类时,可以直接调用类中定义的抽象方法,但是具体的抽象方法内容就必须由子类来提供。

定义一个行为类

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 Human extends Action{
    public void eat() {
        System.out.println("Human supplement energy") ;
    }
    public void sleep() {
        System.out.println("Human begin to sleep") ;
    }
    public void work() {
        System.out.println("Human working hard");
    }
}

定义机器人类

class Robot extends Action{
    public void eat() {
        System.out.println("Robot supplement energy") ;
    }
    public void sleep() {//此操作不需要但必须覆写,所以方法体为空
    }
    public void work() {
        System.out.println("Robot working hard");
    }
}

定义猪的类

class Pig extends Action{
    public void eat() {
        System.out.println("Pig supplement energy") ;
    }
    public void sleep() {
        System.out.println("Pig begin to sleep") ;
    }
    public void work() {
    }
}

测试行为

class TestDemo {
    public static void main(String[] args) {
        fun(new Robot()) ;
        fun(new Human()) ;
        fun(new Pig()) ;
    }   
    public static void fun(Action act) {
        act.command(Action.EAT);
        act.command(Action.SLEEP) ;
        act.command(Action.WORK);         
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值