daily pastebin goal
54%
SHARE
TWEET

Component design pattern for Java

a guest Feb 16th, 2016 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class WidgetComponent {
  2.  
  3.     public static interface Owner {
  4.         WidgetComponent getWidgetComponent();
  5.     }
  6.    
  7.     public static WidgetComponent get(Object o) {
  8.         if (o instanceof Owner) {
  9.             return ((Owner)o).getWidgetComponent();
  10.         }
  11.         return null;
  12.     }
  13.    
  14.     private String m_foo;
  15.    
  16.     public WidgetComponent() {
  17.         m_foo = "bar";
  18.     }
  19.    
  20.     public String getFoo() {
  21.         return m_foo;
  22.     }
  23. }
  24.  
  25. public class Thing implements WidgetComponent.Owner {
  26.  
  27.     private m_widgetComp;
  28.    
  29.     public Thing() {
  30.         m_widgetComp = new WidgetComponent();
  31.     }
  32.    
  33.     @Override
  34.     public WidgetComponent getWidgetComponent() {
  35.         return m_widgetComp;
  36.     }
  37. }
  38.  
  39. public class Main {
  40.  
  41.     public static void main(String[] args) {
  42.    
  43.         // access component from concrete class
  44.         Thing thing = new Thing();
  45.         System.out.println(thing.getWidgetComponent().getFoo());
  46.        
  47.         // access component from abstract class
  48.         // (kind of like instanceof for inheritance trees)
  49.         Object o = (Object)thing;
  50.         WidgetComponent widgetComp = WidgetComponent.get(o);
  51.         if (widgetComp != null) {
  52.             System.out.println(widgetComp.getFoo());
  53.         }
  54.     }
  55. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top