问题描述
看来在Groovy中转换对象的惯例是使用作为
运算符并覆盖 asType()
。例如: class Id {
def value
@Override
public Object AsType(Class type){
if(type == FormattedId){
return new FormattedId(value:value.toUpperCase())
}
}
}
$ b def formattedId = new Id(value:test)as FormattedId
asType()的实现,以便它可以支持像呈现为JSON
。
另一种方法是在Grails Bootstrap类中重写 asType()
如下所示:
def init = {servletContext - >
Id.metaClass.asType = {班级类型 - >
if(type == FormattedId){
return new FormattedId(value:value.toUpperCase())
}
}
}
然而,这会导致代码重复(DRY),因为您现在需要在Bootstrap 和 Id类,否则作为FormattedId
将无法在Grails容器外工作。
Groovy / Grails中的转换代码不会破坏像Single Responsibility Principal或DRY这样的良好代码/ OO设计原则? Mixins在这里很好用吗?
您可以使用Grails支持自动为您的Grails原型添加 encodeAs *
函数:
class FormattedIdCodec {
static encode = {target - >
new FormattedId((target as String).toUpperCase()
}
}
然后您可以在代码中使用以下代码:
def formattedId = new Id(value :test)。encodeAsFormattedId
It appears the convention for converting objects in Groovy is to use the as
operator and override asType()
. For example:
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
However, Grails over-writes the implementation of asType()
for all objects at runtime so that it can support idioms like render as JSON
.
An alternative is to re-write the asType()
in the Grails Bootstrap class as follows:
def init = { servletContext ->
Id.metaClass.asType = { Class type ->
if (type == FormattedId) {
return new FormattedId(value: value.toUpperCase())
}
}
}
However, this leads to code duplication (DRY) as you now need to repeat the above in both the Bootstrap and the Id class otherwise the as FormattedId
will not work outside the Grails container.
What alternatives exist to writing conversion code in Groovy/Grails that do not break good code/OO design principals like the Single Responsibility Principal or DRY? Are Mixins are good use here?
You can use the Grails support for Codecs to automatically add encodeAs*
functions to your Grails archetypes:
class FormattedIdCodec {
static encode = { target ->
new FormattedId((target as String).toUpperCase()
}
}
Then you can use the following in your code:
def formattedId = new Id(value: "test").encodeAsFormattedId
这篇关于在编写转换代码时,有什么替代方法可以覆盖asType()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!