加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 05:22:29 所属栏目:Java 来源:网络整理
导读:我想编写一个只能实例化5次的 java类,就像你只有一个实例的单例类一样. 除此之外,应以循环方式选择实例. 假设我有一个A类.我应该只能创建这个类的5个实例. 假设我有InstanceA_1,InstanceA_2,InstanceA_3,InstanceA_4,InstanceA_5.每当我需要使用它们时,应该
我想编写一个只能实例化5次的 java类,就像你只有一个实例的单例类一样.

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

假设我有一个A类.我应该只能创建这个类的5个实例.
假设我有InstanceA_1,InstanceA_2,InstanceA_3,InstanceA_4,InstanceA_5.每当我需要使用它们时,应该循环选择它们.

解决方法

就像Effective Java 2nd Edition推荐实现单例的枚举一样,这个解决方案也使用枚举来实现… quadrupleton?

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,...
    }
}

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

也可以看看

> Effective Java 2nd Edition,使用私有构造函数或枚举类型强制执行单例属性

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.

相关问题

> Efficient way to implement singleton pattern in Java

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读