We use Java 8 to implement a mixed effect through VEM, But we warn you not to use it at work!
The following implementation is not thread-safe and may cause memory leakage. It depends on the hashcode and equals methods defined in the class. This is also a disadvantage, I will discuss this issue later.
First, we define an interface (simulate state bean) and provide the default definition of the method:
1 public interface switchablemixin {
2 Boolean isactivated () default {return switchables. isactivated (this );}
3 void setactivated (Boolean activated) default {switchables. setactivated (this, activated );}
4}
Then we define a tool class that contains a map instance to save the association between the instance and the status. The status is represented by the private nested class in the tool class:
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}
Here is a use case that highlights state inheritance:
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 ();