Java8对混入的模拟
我们用JAVA8来通过 VEM 实现一个混入效果,不过事先警告的是:请不要在工作中使用!
下面的实现不是线程安全的,而且还可能存在内存泄露问题,这取决于你在类中定义的 hashCode 和 equals 方法,这也是另外一个缺点,我将在后面讨论这个问题。
首先我们定义一个接口(模拟状态Bean)并提供方法的默认定义:
1 public interface SwitchableMixin {
2 boolean isActivated() default { return Switchables.isActivated(this); }
3 void setActivated(boolean activated) default { Switchables.setActivated(this, activated); }
4 }
然后我们定义一个工具类,包含一个 Map 实例来保存实例和状态的关联,状态通过工具类中的私有的嵌套类代表:
01 public final class Switchables {
02
03 private static final Map<SwitchableMixin, SwitchableDeviceState> SWITCH_STATES = new HashMap<>();
04
05 public static boolean isActivated(SwitchableMixin device) {
06 SwitchableDeviceState state = SWITCH_STATES.get(device);
07 return state != null && state.activated;
08 }
09
10 public static void setActivated(SwitchableMixin device, boolean activated) {
11 SwitchableDeviceState state = SWITCH_STATES.get(device);
12 if (state == null) {
13 state = new SwitchableDeviceState();
14 SWITCH_STATES.put(device, state);
15 }
16 state.activated = activated;
17 }
18
19 private static class SwitchableDeviceState {
20 private boolean activated;
21 }
22
23 }
这里是一个使用用例,突出了状态的继承:
1 private static class Device {}
2
3 private static class DeviceA extends Device implements SwitchableMixin {}
4
5 private static class DeviceB extends Device implements SwitchableMixin {}
1 DeviceA a = new DeviceA();
2 DeviceB b = new DeviceB();
3
4 a.setActivated(true);
5
6 assertThat(a.isActivated()).isTrue();
7 assertThat(b.isActivated()).isFalse();
以上是 Java8对混入的模拟 的全部内容, 来源链接: utcz.com/z/389615.html