I want to have only 5 instance of a class throughout the application life time. How can I achieve this? Please give sample code, if possible.
As Singletons shall be made with enums (See "Effective Java"):
public enum FiveInstance {
INSTANCE1, INSTANCE2, INSTANCE3, INSTANCE4, INSTANCE5;
public void anyMethod() {}
}
Greetz GHad
The Factory pattern could be your friend. One (fictional, not threadsafe and thus quite simple) example to illustrate the approach:
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) {
// ...
}
// ....
}
}
EDIT
The license example was not too good - so I moved it to a domain that expects, that objects created by the factory are not returned and destroyed without noticing the factory. The Bar can't create Martinis when there is no olive left and it definitly doesn't want the drink back after it has been consumed ;-)
EDIT 2 And for sure, only the factory can create Instances (=Drinks). (No guarantee, that the added inner private class fulfills this requirement, don't have an IDE at hand to do a quick test .. feel free to comment or edit)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With