gpt4 book ai didi

java - 编写一个 java 类,只创建它的五个实例

转载 作者:搜寻专家 更新时间:2023-11-01 04:00:22 24 4
gpt4 key购买 nike

我想编写一个只能实例化 5 次的 java 类,就像您拥有只有一个实例的单例类一样。

除此之外,应以循环方式选择实例。

假设我有一个类 A。我应该只能创建这个类的 5 个实例。假设我有 InstanceA_1、InstanceA_2、InstanceA_3、InstanceA_4、InstanceA_5。每当我需要使用它们时,都应该在循环法的基础上进行选择。

最佳答案

正如Effective Java 2nd Edition推荐enum来实现单例一样,这个解决方案也使用enum来实现...四元组?

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, MEENIE, MINY, MO, EENIE, MEENIE, MINY, MO, ...
}
}

将其扩展到五元组是不言自明的。

另见

  • Effective Java 2nd Edition,强制使用私有(private)构造函数或枚举类型的单例属性

    As of release 1.5., there is a third approach to implementing singletons. Simply make an enum type with one element. This approach is functionally equivalent to the public field approach, except that it is more concise, provides serialization mechanism for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

相关问题

关于java - 编写一个 java 类,只创建它的五个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3399191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com