Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only 5 instances of a class [closed]

Tags:

java

singleton

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.

like image 298
JavaUser Avatar asked Nov 29 '22 05:11

JavaUser


2 Answers

As Singletons shall be made with enums (See "Effective Java"):

public enum FiveInstance {

  INSTANCE1, INSTANCE2, INSTANCE3, INSTANCE4, INSTANCE5;

  public void anyMethod() {}

}

Greetz GHad

like image 200
GHad Avatar answered Dec 09 '22 20:12

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)

like image 29
Andreas Dolk Avatar answered Dec 09 '22 18:12

Andreas Dolk