java - 单例的抽象基枚举/类 [英] java - Abstract base enum/class for singleton

查看:36
本文介绍了java - 单例的抽象基枚举/类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个 enum 类作为单例:

I've created two enum classes as singleton:

public enum A {
    INSTANCE;

    public void init(param p1, param p2) {
    }

    public void connect() {
    }

    public void disconnect() {
    }

    public bool isConnected() {
    }
}

public enum B {
    INSTANCE;

    public void init(param p1) {
    }

    public void connect() {
    }

    public void disconnect() {
    }

    public bool isConnected() {
    }
}

正如您所看到的,这两个枚举类非常相似,所以我想知道是否应该创建某种基本抽象类/枚举或接口,然后让这两个枚举从中扩展或实现.

As you can see both enum classes are very similar so I was wondering if I should create some kind of base abstract class/enum or interface and then have these two enums extend or implement from it.

更新 1:我想在基类上放置一些共享成员变量

UPDATE 1: I'd like to put some shared member variables on the base class

更新 2:我应该改变定义单例的方式吗?

UPDATE 2: Should I just change the way I'm defining the singleton?

推荐答案

正如 Nambari 所说,你不能让枚举扩展任何东西.然而,他们忽略了你可以让枚举实现一个接口,这与使用 implements 关键字的类一样.我在工作中做过这个,它在正确的情况下非常有用!这里有一个例子:http://javahowto.blogspot.co.uk/2008/04/java-enum-examples.html

As Nambari stated you can't have an enum extend anything. However what they neglected to say is you CAN have an enum implement an interface, which is done as with a class using the implements keyword. I've done this at work and it's very useful in the right situation! There's an example here: http://javahowto.blogspot.co.uk/2008/04/java-enum-examples.html

这篇关于java - 单例的抽象基枚举/类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆