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

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

定义一个行为类

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);         
    }
}

猜你喜欢

转载自blog.csdn.net/guohaocan/article/details/81415904