java之-命令模式

           命名模式首先需要一個只有單一方法的接口,然後從該接口實現具有各自不同的行爲的多個子類,下面給出一個樣例。

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() {
			
			@Override
			public void action() {
				System.out.println("KITCHEN fire!");
			}
		});
		
		em.put(AlarmPoints.BATHROOM, new Command() {
			
			@Override
			public 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 block
			e1.printStackTrace();
		}
	}
}

package java191;

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

EnumMap是一種特殊的Map,它要求其中的鍵(key)必須來自一個enum.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章