Only 5 instances of a class [closed]

2020-03-24 08:03发布

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.

11条回答
对你真心纯属浪费
2楼-- · 2020-03-24 08:39

Look at Object pool pattern. Its java implementation is greatly described in Grand Patterns in Java V1.

Short description from the book overview:

Object Pool

Manage the reuse of objects for a type of object that is expensive to create or only a limited number of a kind of object can be created.

查看更多
爷的心禁止访问
3楼-- · 2020-03-24 08:45

I think you can't. You can force that if somebody want to create or destroy an instance has to use these static methods:

import java.util.*;

public class Fiveton {

    public final static int MAX_INSTANCES = 5;

    private static List<Fiveton> instances = new ArrayList<Fiveton>();


    private Fiveton() { }


    public static Fiveton getInstance() {
        if (instances.size()>=MAX_INSTANCES) throw new RuntimeException("Hey! You've reached the maximum of instances: " + MAX_INSTANCES);
        Fiveton instance = new Fiveton();
        instances.add(instance);
        return instance;
    }

    public static void destroy(Fiveton instance) {
        instances.remove(instance);
    }

}

The problem is method destroy. You can't be sure that someone is still referencing the destroyed object.

查看更多
何必那么认真
4楼-- · 2020-03-24 08:48

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)

查看更多
孤傲高冷的网名
5楼-- · 2020-03-24 08:50

Have a look at the static keyword.

查看更多
Luminary・发光体
6楼-- · 2020-03-24 08:51

You can try following code but written in C#, you can get a basic idea how can it be done.

public  class MultiTone
    {
        private static MultiTone _cache;
        private static int _counter=5;
        MultiTone()
        {

        }
        public static MultiTone GetInstance()
        {
           if(_counter==0)
           {
              return _cache ?? (_cache = new MultiTone());
           }
            _counter--;
            return new MultiTone();
        }
    }

And mind that this class is't intended to use in multi-threading environment.

查看更多
登录 后发表回答