java之-命令模式

来源:互联网 发布:手机淘宝怎么看优惠券 编辑:程序博客网 时间:2024/04/30 11:45

           命名模式首先需要一个只有单一方法的接口,然后从该接口实现具有各自不同的行为的多个子类,下面给出一个样例。

package java191;import java.util.EnumMap;import java.util.Map;import static java191.AlarmPoints.*;interface Command {void action();}public class EnumMaps {public static void main(String[] args) {EnumMap<AlarmPoints, Command> em = new EnumMap<AlarmPoints, Command>(AlarmPoints.class);em.put(AlarmPoints.KITCHEN, new Command() {@Overridepublic void action() {System.out.println("KITCHEN fire!");}});em.put(AlarmPoints.BATHROOM, new Command() {@Overridepublic void action() {System.out.println("Bathroom alert");}});for(Map.Entry<AlarmPoints, Command> e : em.entrySet()){System.out.println(e.getKey()+": ");e.getValue().action();}try {em.get(UTILITY).action();} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}}

package java191;public enum AlarmPoints {STAIR1, STAIR2, LOBBY, OFFICE1, OFFICE2, OFFICE3, OFFICE4, BATHROOM, UTILITY, KITCHEN}

EnumMap是一种特殊的Map,它要求其中的键(key)必须来自一个enum.

0 0
原创粉丝点击