何时使用自引用或组合? [英] When to use self references or composition?

查看:34
本文介绍了何时使用自引用或组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看下面的代码片段:

trait T { def y = println("hello") }
class A {
   self: T =>
   def x = y
}
abstract class B {
   val self: T
   def x = self.y
}

val a = new A with T
val b = new B with T {
   val self = this
}
a.x
b.x

类 A 和 B 有一个对特征 T 的引用,A 有一个自引用,B 有一个引用正在使用组合.

Class A and B have a reference to trait T, A has a self reference and B is using composition.

我在这里只看到两个区别:第一个是创建新对象第二个是访问 T.

I see only two differences here: The first is in creating new objects and the second in accessing T.

在 B 中有更多的语法糖,我不需要显式访问引用 self 并且我不需要绑定变量.

In B there is more syntactic sugar, I don't need to explicitly access reference self and I don't need to bind the variable.

是否还有其他不同之处?是否在某些情况下应该首选而不是另一个?

Are there another differences and are there some situations in which one should preferred instead of the other?

推荐答案

您的问题似乎排除了普通继承.对于A,self 类型与class A extends T 相比没有优势.对于 B,如果你打算只按照编写的方式创建它,即使用 self = this,extends 也一样好(而且简单得多)

Your question seems to excludes plain inheritance. For A, the self type has no advantage compared to class A extends T. For B, if you intend to create it only as written, that is with self = this, extends is just as good too (and so much simpler)

我认为 self 类型的用例并不多(但这不是组合与继承的讨论)

I don't think there are that many use case for self type (but this is not a discussion of composition vs inheritance)

其中之一是强制将特征实例化为另一种未知类型的子类型,因为它作为类型参数或抽象类型成员出现.例如,trait X[A] {self: A =>...} 你可以看看这个现实的例子scala 站点,具有类型成员.

One of them is to force a trait to be instanciated only as a subtype of another type not yet known, because it appears as a type parameter or an abstract type member. For instance, trait X[A] {self: A => ...} You can have a look at this realistic example on the scala site, with a type member.

另一种情况是当您组合模块而不是实例时,特别是当模块具有类型成员时,使得组合仅在编译时可行.这或多或少与 CakePattern 相关.

Another is when you are composing modules, rather than instances, in particular when module have type members, making composition feasible only at compile time. This is more or less related to the CakePattern.

组合(无论是带有抽象 val 还是构造函数参数)当然具有强大的优势,您可以传递 T 的外部实例,在 B 的不同实例之间共享它,更动态地选择它.实例可以传递给函数和从函数返回,mixin 不能

Composition (whether with abstract val or constructor parameter) has of course the strong advantage that you can pass an external instance of T, share it between different instances of B, choose it much more dynamically. instances may be passed to and returned from functions, mixins cannot

这篇关于何时使用自引用或组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆