标签:设计 bre cas 机器人 pig 定义 color switch 工作
模板设计模式(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); } }
标签:设计 bre cas 机器人 pig 定义 color switch 工作
原文地址:http://www.cnblogs.com/hu1056043921/p/7327034.html