我們用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();