gpt4 book ai didi

grails - 在编写转换代码时,有哪些替代方法可以替代 asType() ?

转载 作者:行者123 更新时间:2023-12-02 00:47:59 25 4
gpt4 key购买 nike

看来 Groovy 中转换对象的约定是使用 as 运算符并覆盖 asType()。例如:

class Id {
def value

@Override
public Object asType(Class type) {
if (type == FormattedId) {
return new FormattedId(value: value.toUpperCase())
}
}
}

def formattedId = new Id(value: "test") as FormattedId

但是,Grails 在运行时覆盖了所有对象的 asType() 实现,以便它可以支持 render as JSON 等习惯用法。

另一种方法是在 Grails Bootstrap 类中重写 asType(),如下所示:

def init = { servletContext ->
Id.metaClass.asType = { Class type ->
if (type == FormattedId) {
return new FormattedId(value: value.toUpperCase())
}
}
}

但是,这会导致代码重复 (DRY),因为您现在需要在 Bootstrap 和 Id 类中重复上述操作,否则 as FormattedId 将无法工作在 Grails 容器之外。

除了在 Groovy/Grails 中编写转换代码之外,还有哪些替代方案不会破坏良好的代码/OO 设计原则(例如单一职责原则或 DRY)? Mixin 在这里有用吗?

最佳答案

您可以使用 Grails 支持 Codecs自动将 encodeAs* 函数添加到您的 Grails 原型(prototype)中:

class FormattedIdCodec {

static encode = { target ->
new FormattedId((target as String).toUpperCase()
}

}

然后您可以在代码中使用以下内容:

def formattedId = new Id(value: "test").encodeAsFormattedId

关于grails - 在编写转换代码时,有哪些替代方法可以替代 asType() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14243525/

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