GHa*_*Had 12
由于单身人士应使用枚举(参见"有效Java"):
public enum FiveInstance {
INSTANCE1, INSTANCE2, INSTANCE3, INSTANCE4, INSTANCE5;
public void anyMethod() {}
}
Run Code Online (Sandbox Code Playgroud)
格雷茨GHad
工厂模式可能是你的朋友.一个(虚构的,不是线程安全的,因而非常简单)的例子来说明这种方法:
public static MartiniFactory {
private static int olives = 100; // you asked for '5' but 100 is more realistic
// for this example.
public static Drink createMartini() throws OutOfOlivesException {
if (olives > 0) {
olives--;
return new Martini(new Gin(4), new Vermouth(1), new Olive());
else {
throw new OutOfOlivesException();
}
}
// forgot to mention, only the factory (=bar) is able to create Martinis, so:
private class Martini {
Martini(Ingredient... ingredients) {
// ...
}
// ....
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
许可证示例并不太好 - 所以我将其移动到一个域,该域期望工厂创建的对象不会在不注意工厂的情况下返回和销毁.当没有剩下的橄榄时,酒吧不能创造马提尼酒,它绝对不希望饮料在消费后回来;-)
编辑2 当然,只有工厂可以创建实例(=饮料).(无法保证,增加的内部私有类符合此要求,没有IDE可以快速进行测试..随意评论或编辑)