Write a Java class and create only five instances of it

I want to write a Java class that can only be instantiated five times, just like a singleton class with only one instance

In addition, instances should be selected in a circular manner

Suppose I have a class A I should only be able to create 5 instances of this class Suppose I have instancea_ 1,InstanceA_ 2,InstanceA_ 3,InstanceA_ 4,InstanceA_ 5. Whenever I need to use them, I should cycle through them

Solution

Just as effective Java 2nd Edition recommends enumerating singletons, this solution also uses enumerations to implement... Quadripleton?

import java.util.*;

public enum RoundRobin {
    EENIE,MEENIE,MINY,MO;

    private final static List<RoundRobin> values =
        Collections.unmodifiableList(Arrays.asList(values()));
    // cache it instead of creating new array every time with values()

    private final static int N = values.size();
    private static int counter = -1;

    public static RoundRobin nextInstance() {
        counter = (counter + 1) % N; // % is the remainder operator
        return values.get(counter);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(RoundRobin.nextInstance());
        }
        // EENIE,MO,EENIE,...
    }
}

It is self - evident to extend it to quintuples

You can also have a look

>Effective Java 2nd Edition, which enforces singleton properties using private constructors or enumeration types

Related issues

> Efficient way to implement singleton pattern in Java

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>