如何实现有效的Java特性? [英] Ways to achieve effective Java traits?

查看:96
本文介绍了如何实现有效的Java特性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是不合适的,请告诉我(特别是Programmers.SE是否会更好地解决问题。)

Please let me know if this is inappropriate as formulated (in particular whether Programmers.SE or something would be better for the question.)

好的。所以我有很多'特征',我目前正在表达为接口。我们称之为可更新和可破坏。将它们表示为接口有一个缺点,我无法在所有可破坏组件之间共享行为;另一方面,将这些表示为抽象类意味着我不能混合和匹配而不将混合特征明确定义为另一个抽象类(UpdateableAndDestructible),而且这感觉就像滥用抽象类功能一样。但是,如果没有更简洁的方法来解决这个问题,我可能最终会这样做。

Alright. So I've got a number of 'traits' that I'm currently expressing as interfaces. Let's call them "updatable" and "destructible". Expressing them as interfaces has the downside that I can't share behavior between all "destructible" components; on the other hand, expressing these as abstract classes mean I can't mix and match without explicitly defining the mixed trait as another abstract class ("UpdateableAndDestructible") and furthermore this feels like an abuse of the abstract class functionality at that point. It's probably what I'll end up doing if there aren't cleaner ways of handling this, however.

对于这个难题,纯Java解决方案有哪些选择? ?我是否有可能描述共享行为,然后按照我认为合适的方式进行混合和匹配,而不必明确描述我将要使用的每个排列?

What are my options as far as pure Java solutions to this conundrum? Is it possible for me to describe shared behavior and then mix and match as I see fit without having to explicitly describe every permutation I'll be using?

推荐答案

也许你可以通过使用混合接口和默认实现来实现目标。

Maybe you could achieve the goal by using a mix of interfaces and default implementations.

赞:

public interface Updatable {
  void updated();
}

public interface Loadable {
  void load();
}

public class DefaultUpdatable implements Updatable {
 ...
}

public class DefaultLoadable implements Loadable {
 ...
}

public class SomeObject implements Updatable, Loadable {
  private final Updatable updatable = new DefaultUpdatable();
  private final Loadable loadable = new DefaultLoadable();

  public void load() {
    this.loadable.load();
  }

  public void updated() {
    this.updatable.updated();
  }
}

仍然很嘈杂,可能没有您想要的那么灵活但也许比使用UpdatableAndDestructable更清洁。

Still noisy and maybe not as flexible as you would like but maybe a bit cleaner than doing the UpdatableAndDestructable thing.

这篇关于如何实现有效的Java特性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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