Java Constructor Injection -
let's have class resources
instantiates of opengl / java game objects , pass these via constructor scene class (which requires them), (simplified example).....
public class resources { hero hero; enemy enemy; menubuttons mainmenubuttons; background background; scene mainmenu; public void createobjects(){ hero = new hero(); enemy = new enemy(); mainmenubuttons = new menubuttons(); background = new background(); mainmenu = new scene(hero, enemy, mainmenubuttons, background); } }
obviously scene's constructor need take 4 arguments so:
public class mainmenu implements scene { hero hero; enemy enemy; mainmenubuttons menubuttons; background background; public mainmenu(hero hero, enemy enemy, mainmenubuttons mainmenubuttons, background background){ this.hero = hero; this.enemy = enemy; this.mainmenubuttons = mainmenubuttons; this.background = background; } }
as more objects required, constructor grows ever longer. let's following instead:
public class mainmenu implements scene { resources resources; public mainmenu(resources resources){ this.hero = resources.hero; this.enemy = resources.enemy; this.mainmenubuttons = resources.mainmenubuttons; this.background = resources.background; } }
both options allow me use objects within mainmenuscene so:
hero.move();
the 2nd seems little neater constructor never need take additional arguments. however far can recall, i've never seen examples this. valid technique? run problems using it?
short answer:-yes technique valid , should work fine.
longer part:-
suggest 2 design approaches consider
the essence pattern
the fluent interface pattern
these both similar in intent.
also builder pattern can helpful. see many times using hibernate. class below:-
public class mainmenu implements scene { private hero hero; private enemy enemy; private menubuttons mainmenubuttons; private background background; public mainmenu sethero(hero hero){this.hero = hero; return this} public mainmenu setenemy(enemy enemy){this.enemy = enemy; return this} public mainmenu setmainmenubuttons(menubuttons mainmenubuttons){this.mainmenubuttons = mainmenubuttons; return this} public mainmenu setbackground(background background){this.background = background; return this} }
and create objects using chaining below:-
mainmenu main =new mainmenu(). sethero(new hero()). setenemy(new enemy()). setmainmenubuttons(new mainmenubuttons()). setbackground(new background());
p.s. if don't want use above patterns recommend 3 changes or habits.
1. class name start uppercase alphabet and
2. convention of organizing arguments alphabetically.
3. want set acces level of members private.
Comments
Post a Comment