有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java对命名模式的建议,该模式在op失败时尝试强制转换返回null

我在很多地方见过这种模式,但从未见过它的名字

我更多的是想知道如何命名实现它的方法,因为不同的人似乎使用不同的命名模式

抱歉,我想不起任何图书馆作为例子,但如果使用一个作为你的答案的一部分,请命名它们

public class Produce{

   package private Produce(){};

   Fruit isFruit(){
     return null;
   }
   Veg isVeg(){
     return null;
   } 
}

public class Veg extends Produce {

   package private Veg(){};

   Veg isVeg(){
     return this;
   }
}

public class Fruit extends Produce {

    package private Fruit(){};

   Fruit isFruit(){
     return this;
   }
}

额外的

@LouisWasserman

首先,通过将产品包装私有化来限制子类型的数量。通过包含2个isXXX方法,我说明了一个事实,即只有2个子类,这比执行instanceof检查更好。也许只是我,但这种方法也意味着在其他代码或上面的代码中没有强制转换,这一定是件好事吧

另外,当搜索或查询失败时,从方法返回一个空列表,这是否与在尝试将Veg转换为水果时返回null以标记操作isFruit()失败相同

我在GWT的JType中找到了一个快速的例子,我相信它是EclipseJDT的克隆。不管怎么说,产地并不重要,但这里我们有两个非常熟悉的产品,正是我所描述的

http://code.google.com/p/google-web-toolkit/source/browse/trunk/dev/core/src/com/google/gwt/core/ext/typeinfo/JType.java

还有很多其他的isXXX会尝试强制转换或返回null,我在下面贴了一些

/**
* Returns this instance as a {@link JAnnotationType} if it is an annotation
* or <code>null</code> if it is not.
*/
JAnnotationType isAnnotation();

JArrayType isArray();

JClassType isClass();

JClassType isClassOrInterface();

/**
* Returns this instance if it is an enumeration or <code>null</code> if it is
* not.
*/
JEnumType isEnum();

JGenericType isGenericType();

共 (1) 个答案

  1. # 1 楼答案

    首先,我认为这是一种可怕的模式。超级类通常应该而不是知道它的子类

    如果添加另一个子类Produce,会怎么样?你需要记住修改Produce。容易出错

    不过,为了回答您的问题,我会避免使用^{,因为用户可能希望它返回布尔值。如果被迫使用这种模式,我可能会使用getFruit()asFruit()