java模式之模板模式——抽象类
模板设计模式(Template )
abstract class Action{ // 定义一个行为类 public static final String WORK = "work"; public static final String SLEEP = "sleep"; public static final String EAT = "eat"; public abstract void eat(); public abstract void sleep(); public abstract void work(); public void command(String str){ switch(str){ case "work": this.work(); break; case "sleep": this.sleep(); break; case "eat": this.eat(); break; } } } class People extends Action{ public void sleep(){ System.out.println("人正在睡觉"); } public void eat(){ System.out.println("人正在吃饭"); } public void work(){ System.out.println("人正在工作"); } } class Pig extends Action{ public void sleep(){ System.out.println("猪正在睡觉"); } public void eat(){ System.out.println("猪正在吃饭"); } public void work(){ } } class Robot extends Action{ public void sleep(){ } public void eat(){ System.out.println("机器人正在补充能量"); } public void work(){ System.out.println("机器人正在工作"); } } public class Test{ public static void main(String args[]){ fun(new People()); fun(new Robot()); } public static void fun(Action act){ act.command(act.WORK); act.command(act.SLEEP); act.command(act.EAT); } }