Java8對混入的類比

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.