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:28

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

public enum FiveInstance {

  INSTANCE1, INSTANCE2, INSTANCE3, INSTANCE4, INSTANCE5;

  public void anyMethod() {}

}

Greetz GHad

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

Create a private static member to count the instances of the class. Then, make sure every constructor of your class increment this static variable and test for overflow. If you have more than one constructor I suggest that you make one constructor implement this behaviour and the others should call it. The behavior of the constructor upon an attempt to create a sixth instance is up to you. Maybe you want to throw an Exception.

查看更多
Bombasti
4楼-- · 2020-03-24 08:36

There is a pattern called a Multiton which deals with this, as an extension of Singleton. Nobody seems quite clear it it's a pattern in its own right or a variation on Singleton. Check out the link, it includes sample code.

查看更多
在下西门庆
5楼-- · 2020-03-24 08:36

Create a static field called howMany which will be incremented each time that the constructor is called.

When howMany is => 5, deny creation of the object.

查看更多
一夜七次
6楼-- · 2020-03-24 08:38
class Sample
{
   private static int i = 0;

   private Sample()
   {
   } 

  public static Sample CreateInstance()
   {
      if(i <5)
      {
          i++;
          return new Sample();
      } 

      else
        throw new Exception("Can not create more then 5 instance of this class");  
   }

}
查看更多
男人必须洒脱
7楼-- · 2020-03-24 08:39
public class FiveInstance {
    private static int instanceCount = 0;
    private FiveInstance(){
    }
    public static FiveInstance getNewInstance() throws InstanceExceededException{
        if(instanceCount < 5){
            instanceCount++;
            return new FiveInstance();
        }else{
            throw new InstanceExceededException();
        }
    }
}
查看更多
登录 后发表回答