Advertisement
DulcetAirman

Java 8 Interface with state

Oct 25th, 2013
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. ////////////////////////////////////////////////////////
  2. package ch.claude_martin.java8.mixins;
  3.  
  4. import java.util.IdentityHashMap;
  5.  
  6. public interface FooBar {
  7.   static class Data {
  8.     int foo = 0;
  9.     String bar = "";
  10.   }
  11.   // TODO : Should be some kind of WeakIdentityHashMap!
  12.   final static IdentityHashMap<FooBar, Data> _map = new IdentityHashMap<>();
  13.  
  14.   static Data get(FooBar foobar) {
  15.     return _map.computeIfAbsent(foobar, x -> new Data());
  16.   }
  17.  
  18.   default int getFoo() {
  19.     return get(this).foo;
  20.   }
  21.  
  22.   default void setFoo(int foo) {
  23.     get(this).foo = foo;
  24.   }
  25.  
  26.   default String getBar() {
  27.     return get(this).bar;
  28.   }
  29.  
  30.   default void setBar(String bar) {
  31.     get(this).bar = bar;
  32.   }
  33.  
  34. }
  35. ////////////////////////////////////////////////////////
  36. ////////////////////////////////////////////////////////
  37. package ch.claude_martin.java8.mixins;
  38.  
  39. import java.awt.event.ActionEvent;
  40. import java.awt.event.ActionListener;
  41.  
  42. public class MixinUsage {
  43.  
  44.     public static void main(String... args) {
  45.         MyActionListener foobar = new MyActionListener();
  46.         foobar.setFoo(42);
  47.         foobar.setBar("Hello");
  48.         foobar.actionPerformed(null);
  49.     }
  50.  
  51.     static class MyActionListener implements ActionListener, FooBar {
  52.  
  53.         @Override
  54.         public void actionPerformed(ActionEvent e) {
  55.             System.out.println("foo: " + getFoo());
  56.             System.out.println("bar: " + getBar());
  57.         }
  58.  
  59.     }
  60. }
  61.  
  62.  
  63. ////////////////////////////////////////////////////////
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement