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

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

问题描述

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

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天全站免登陆