1

我有一些在我的几个域类中通用的方法。我想减少重复代码的数量,我想到了两个解决方案:

1)将常用方法放在 baseDomain 类中,并在我的域中从它继承方法
2)将常用方法放在我可以导入到我的 commonDomainMethodService 中域

我想我应该不理会继承,除非域共享公共属性,但我不确定。这些方法中的一种是否比另一种更有益?是否更符合 Grails 最佳实践?

例如,基于参数比较两个域实例的方法:

int compareInstances(instance, otherInstance, propertyName){
    return //some logic to compare the instances based on the type of property
}
4

1 回答 1

3

对于这种情况,我会使用MixinMixin Reading and Further Mixin Reading

例如:

@Mixin(MyCompare)
class DomainA {
}

@Mixin(MyCompare)
class DomainB {
}

class MyCompare {

    def compare(instance1, instance2, propertyName) {
        instance1[propertyName] == instance2[propertyname]
    }
}

现在 DomainA 和 DomainB 的所有实例都会有你的compare方法。这样,您可以实现多个 Mixin 以向您想要的域类添加功能,而无需扩展超类或在服务中实现它。(我假设您希望您的compare方法比这更复杂一点,但您明白了)

一些潜在的陷阱:

1) 's 中的私有方法mixin似乎不起作用。

2)具有mixin's 的循环依赖也很糟糕: MixinClassA 混合在 MixinClassB 中,而 MixinClassB 混合在 MixinClassA 中(对于您的设置,我认为您不会mixin在其他mixin's 中混合)。

3)我忘记了方法冲突会发生什么,所以你应该尝试一下。示例:ClassA 有一个 doStuff() 方法并在 DoStuffMixin 中混合,后者也有一个 doStuff() 方法。

4) 请记住,在您用作 a 的类中,您mixin可以引用this哪个将是使用mixin. 例如,在上面的示例中,您可以删除 并将其instance1替换为this. 在运行时this将是 DomainA 或 DomainB 的实例(我觉得这是 mixins 的一个非常强大的部分)。

这些是我能想到的大问题。

于 2012-04-12T15:49:51.300 回答