创建DRY枚举

时间:2014-07-24 14:40:46

标签: java groovy enums

我想使用 Groovy 2.1.9 在几个不同的枚举之间分享类似的功能。枚举都用于生成XML,因此我给了它们一个名为xmlRepresentation的属性。以下是两个枚举:

enum Location {
    CollegeCampus('College Campus'), HighSchool('High School'), Online('Online')

    Location(String xmlRep) {
        this.xmlRepresentation = xmlRep
    }

    String toString() {
        xmlRepresentation
    }

    String xmlRepresentation
}


enum InstructorType {
    CollegeFaculty('College Faculty'), HighSchoolFaculty('High School Faculty')

    InstructorType(String xmlRep) {
        this.xmlRepresentation = xmlRep
    }

    String toString() {
        xmlRepresentation
    }

    String xmlRepresentation
}

如您所见,我必须在这两个枚举中声明xmlRepresentation属性,toString方法和构造函数。我想分享这些属性/方法,但我不认为我可以继承枚举。我尝试过使用mixin而没有任何运气:

class XmlRepresentable {

    String xmlRepresentation

    XmlRepresentable(String xmlRepresentation) {
        this.xmlRepresentation = xmlRepresentation
    }

    String toString() {
        this.xmlRepresentation
    }
}


@Mixin(XmlRepresentable)
enum Location {
    CollegeCampus('College Campus'), HighSchool('High School'), Online('Online')
}

这产生了错误Could not find matching constructor for: com.company.DeliveryFormat

有谁知道我如何分享这项功能并让我的代码干嘛?谢谢!

1 个答案:

答案 0 :(得分:5)

这是移动到Groovy 2.3.0及更高版本的一点动机。 :)使用trait

的一些DRYness
trait Base {
    final String xmlRepresentation

    void setup(String xmlRep) {
        this.xmlRepresentation = xmlRep
    }

    String toString() {
        xmlRepresentation
    }

    String getValue() {
        xmlRepresentation
    }
} 

enum Location implements Base {
    CollegeCampus('College Campus'), HighSchool('High School'), Online('Online')
    Location(String xmlRep) { setup xmlRep }
}

enum InstructorType implements Base {
    CollegeFaculty('College Faculty'), HighSchoolFaculty('High School Faculty')
    InstructorType(String xmlRep) { setup xmlRep }
}

assert Location.HighSchool in Location
assert Location.Online.value == 'Online'
assert InstructorType.CollegeFaculty in InstructorType

我认为你现在拥有的AFAIK没有什么可以做的。