java - How to share properties between class instances and other possible users of those properties? -


say there multiple classes {c1, c2, ...} implement interface i, containing, among other things, methods called getcolor(), getname(), , move(). every instance of c1 returns same value when getcolor() , getname() called, same c2 , of other classes implement i. move defined per class, too, affected instance variables , may not behave same way per instance. implementations of getcolor() , getname() in c1 class might like:

public color getcolor() {     return color.red; }  public string getname() {     return "c1!!!"; } 

all objects implementing interface i can added , drawn screen. suppose, however, way in objects added, through different screen, buttons on it. when 1 of buttons clicked, signals application type of object associated clicked should added screen.

if goal label button associated c1 string returned c1's getname() , color button color returned c1's getcolor(), 1 instantiate new instance of c1, , retrieve name , color customize associated button:

... instance = new c1(); button c1button = new button(); c1button.setlabel(instance.getname()); c1button.setcolor(instance.getcolor()); ... 

... , instantiate new instance of c2 , c3 , ... , c50, following same process c1.

this seems rather dirty though, classes no longer being instantiated sake of fulfilling other methods in i, obtain color , name properties buttons. furthermore, awful lot of code. can provide suggestions how color , name properties decoupled classes implementing i, reduce length of code required if number of classes implementing i grows dramatically past two? there specific design patterns might used resolve this?

i sort of thing making enum this, separate implementation classes

public enum typeofc {     c1(color.red, c1::new),     //you don't have use different classes every one!     cx(color.black, () -> new c1(5)),     c2(color.blue, c2::new);      private final color m_color;     private final supplier<i> m_constructor;      typeofc(color color, supplier<i> ctor)     {         m_color = color;         m_constructor = ctor;     }      public color getcolor()     {         return m_color;     }      public create()     {         return m_ctor.get();     } } 

then can make buttons like:

for (typeofc t : typeofc.values()) {     button b = new button();     b.setcolor(t.getcolor());     b.setlabel(t.name());  // make different getter if don't want enum constant name     b.setaction(()->dowatever(t.create()));     allbuttons.add(b); } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -