Simulation of Java 8

Source: Internet
Author: User

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 ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.