如何创建扩展 class 并实现接口的通用 java class?

how to create generic java class that extends class and implements interface?

我在我的 android 项目结构中使用 DDD,在某些域中,我需要创建一个名为 "behavior" 的新文件夹以将所有屏幕行为放在该文件夹中,就像这样 "public class profileBehavior { .. }"

项目打印:http://tinypic.com/view.php?pic=r1hppi&s=8#.VPDdSlPF_rc

随着时间的推移和针对重用的改进,我正在考虑用常用方法创建一个 "genericBehavior",比如:

public class GenericBehavior {

private static Context context;
private static View view;

public GenericBehavior(Context context) {
    context = context;
}
public GenericBehavior(View view) {
    view = view;
}

public static GenericBehavior with(final Context context) {


    return new GenericBehavior(context);
}

public GenericBehavior where(final View view) {
    return new GenericBehavior(view);
}

并且在 profileBehavior class 中,我希望重用 withwhere 方法来设置 profileBehavior 上下文和查看

喜欢:

public class ProfileBehavior extends GenericBehavior {


public ProfileBehavior(Context context) {
    super(context);
}

我希望在 profileFragment 中使用:

ProfileBehavior
            .with(getActivity())
            .where(rootView)
            .listenAttachOptions()
            .doScrollStuff();

我阅读了有关类型参数和接口的内容,但对此我真的很困惑。就我而言,最好在行为中复制方法或对此有解决方案?

是的,您可以这样做,尽管您希望修改或附加实例变量而不是替换静态变量,并且 return this 不是新实例或至少是包装旧实例的实例return new GenericBehavior(context, this); ... GenericBehavior 可能应该是 ProfileBehavior 实现的一个接口,这样您就可以让 ProfileBehavior 扩展您想要操作的其他一些 class。

(我能想到的)三种方法:

  1. 通过创建基础 class(可以是抽象的)并在该基础中实现 where()with() class 并扩展它。
  2. 如果你使用 Java 8 你会得到 default methods(你 可以 在接口中有方法的默认实现)
  3. Composition:您可以创建一个实现 where()with() 的对象(行为 "base" 对象)并具有 [=36= 的任何其他实例] class 持有此类基础对象的实例作为私有成员。每个这样的 class 都会将每个 where()with() 调用委托给这个基础对象。

#3 的实施示例:

class BaseBehavior implement Behavior {
    public Behavior with(final Context context) {
        return new BaseBehavior(context);
    }

    public Behavior where(final View view) {
        return new BaseBehavior(view);
    }
}

class AnotherBehavior implement Behavior {
    BaseBehavior base;    

    AnotherBehavior(BaseBehavior base) {
        this.base = base;
    }

    public Behavior with(final Context context) {
        return base.with(context);
    }

    public Behavior where(final View view) {
        return base.with(view);
    }        
}

一般来说,组合优于继承(因此,如果您不使用 Java 8 - 使用 #3 比使用 #1 更好),原因有很多,仅举几例: 更易于调试和维护,代码解耦更少,层次结构更简单,您只能继承(扩展)一个 class。