Inheritance or Service for common Domain methods?

可紊 提交于 2019-12-04 19:59:06

For that case I would use a Mixin: Mixin Reading and Further Mixin Reading

For example:

@Mixin(MyCompare)
class DomainA {
}

@Mixin(MyCompare)
class DomainB {
}

class MyCompare {

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

Now all instances of DomainA and DomainB would have your compare method. This way you can implement multiple Mixins to add functionality to the domain classes that you want to without having to extend a super class or implement it in a service. (I'd assume that you'd want your compare method to be a little more sophisticated than this but you get the idea)

Some potential Gotchas:

1) private methods within mixin's seem to not work.

2) having a circular dependency of mixin's is also bad: MixinClassA mixes in MixinClassB which mixes in MixinClassA (for your setup I don't think you would have mixin's mixing in other mixin's).

3) I forget what happens with a method collision so you should probably experiment. Example: ClassA has a doStuff() method and mixes in DoStuffMixin which also has a doStuff() method.

4) Keep in mind that in a class that you're using as a mixin you can refer to this which will be the instance of the object that is using the mixin. For instance in the example above you could remove the instance1 and replace it with this. At runtime this will be either an instance of DomainA or DomainB (which I feel is a very powerful part of mixins).

Those are the big gotchas I can think of.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!