《Effective Java讀書筆記》--C語言結構的替代

用類來代替enum結構

在要求使用一個枚舉類型的環境下,咱們首先應該考慮類型安全枚舉模式。 java

// 這是類型安全枚舉模式的一個簡單實現。
public class Suit {
	private final String name;
	private Suit(String name) {
		this.name = name;
	}
	
	public String toString() {
		return this.name;
	}
	
	public static final Suit CLUBS = new Suit("clubs");
	public static final Suit DIAMONDS = new Suit("diamonds");
	public static final Suit HEARTS = new Suit("hears");
	public static final Suit SPADES = new Suit("spades");
}

用類和接口代替函數指針

在C語言標準庫中的qsort,該函數要求一個指向comparator函數的指針做爲參數,它用這個函數來比較排序的元素。這種用途其實是實現了Strategy模式。爲了在JAVA中實現這種模式,聲明一個接口來表示該策略,而且爲每一個具體策略聲明一個實現了該接口的類。 安全

比較器的實現請參考 http://my.oschina.net/u/1453800/blog/232712 的匿名類這一節。 函數

相關文章
相關標籤/搜索