DulcetAirman icon

Java 8 Interface with state

DulcetAirman | PRO | 10/25/13 09:27:10 AM UTC | 0 ⭐ | 518 👁️ | Never ⏰ | []
Java |

1.44 KB

|

None

|

0 👍

/

0 👎

////////////////////////////////////////////////////////
package ch.claude_martin.java8.mixins;
 
import java.util.IdentityHashMap;
 
public interface FooBar {
  static class Data {
    int foo = 0;
    String bar = "";
  }
  // TODO : Should be some kind of WeakIdentityHashMap! 
  final static IdentityHashMap<FooBar, Data> _map = new IdentityHashMap<>();
 
  static Data get(FooBar foobar) {
    return _map.computeIfAbsent(foobar, x -> new Data());
  }
 
  default int getFoo() {
    return get(this).foo;
  }
 
  default void setFoo(int foo) {
    get(this).foo = foo;
  }
 
  default String getBar() {
    return get(this).bar;
  }
 
  default void setBar(String bar) {
    get(this).bar = bar;
  }
 
}
////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
package ch.claude_martin.java8.mixins;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
public class MixinUsage {
 
    public static void main(String... args) {
        MyActionListener foobar = new MyActionListener();
        foobar.setFoo(42);
        foobar.setBar("Hello");
        foobar.actionPerformed(null);
    }
 
    static class MyActionListener implements ActionListener, FooBar {
 
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("foo: " + getFoo());
            System.out.println("bar: " + getBar());
        }
 
    }
}
 
 
////////////////////////////////////////////////////////

Comments