通过将新类型指定为实际类型的泛型来扩展泛型有什么好处 [英] What is the benefit of extending a generic by specifying the new type as actual type of generic

查看:89
本文介绍了通过将新类型指定为实际类型的泛型来扩展泛型有什么好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class A extends B< A> {

}

这个结构有点不同寻常,将新类型指定为通用实际类型。有什么用?这种模式有没有名字?有没有其他的模式?

示例: https:// code.google.com/p/selenium/wiki/LoadableComponent



跳转到: public class EditIssue extends LoadableComponent< EditIssue> {b} b
$ b

编辑:
阅读完回复后,似乎需要改变我对编译器对类型检查的理解。在我的脑海里,我的牛肉有这种模式,如果两个A的需要相同,那么有没有办法不重复它们?但似乎没有更好的方式将派生类的类型传播给父类。

解决方案

当然,OOP答案是 A 是一个 B 。如果 A 不是 B 而不是 A 本身带有 B 以利用 B 的功能。



假设 B 也有一些通用的实现,它们利用了对泛型的限制。

另一个用例是: B 看起来像这样:

  abstract类B< T扩展了B>> {
public T createCopy(T t);

$ / code>

现在子类可以实现 createCopy 和客户端代码可以安全地使用它,而不必投射......例如,

  class A extends B< A> {
public createCopy(A t){
return new A(t); //复制构造函数


code $

$ b $ p比较上面的内容: p>

 抽象类B {
public B createCopy(B t);
}
class A extends B {
public B createCopy(B t){//复制是A还是B的不同子类型?我们不知道。
返回新的A(t); //复制构造函数
}
}


I saw this pattern somewhere:

class A extends B<A> {

}

This structure is a little unusual to extend a generic by specifying the new type as actual type of generic. What is the use? Is there a name for this pattern? Is there any alternative pattern?

Example: https://code.google.com/p/selenium/wiki/LoadableComponent

Jump to: public class EditIssue extends LoadableComponent<EditIssue> {

Edit: After reading the responses, it seems that I need to alter my understanding of type checking by the compiler. At the back of my mind, my beef with this pattern was, if the two A's need to be same then is there a way to not repeat them? But it seems that there is no better way to propagate the derived class's type to the parent.

解决方案

Of course the OOP answer is that A is a B. If A were not a B than A should merely compose itself with a B to make use of B's functionality.

Presumably B also has some general implementations which take advantage of restrictions placed on the generic type.

Another use case would be for B to look something like:

abstract class B<T extends B<T>> {
    public T createCopy(T t);
}

Now subclasses can implement createCopy and client code can safely use it without having to cast... e.g.

class A extends B<A> {
    public A createCopy(A t) {
        return new A(t); //copy constructor
    }
}

Compare the above to:

abstract class B {
    public B createCopy(B t);
}
class A extends B {
    public B createCopy(B t) { //Is the copy an A or a different subtype of B? We don't know.
        return new A(t); //copy constructor
    }
}

这篇关于通过将新类型指定为实际类型的泛型来扩展泛型有什么好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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