is there way let multiple class share same instance of class? in c# program i've got 3 class gamelogic(a), fpscontroller(b), , spawnplayer(c).
in case class b , c use , alter variables in a, in order use variables i'm instantiating in 2 different classes , use dot notation access variable instance of a, problem after instantiated in different classes, change in instance.variable not share between b , c class @ all.
would static type way of solving this? or writing main better.
any suggestions appreciated.
there few ways. here one:
one way dependency injection. can pass instance of along constructors of b , c (or setter/property of b , c):
a = new a(); b b = new b(a); c c = new c(a);
but doesn't allow change reference in both objects easily, seems problem. 1 way change reference, wrap reference in object somehow.
a nice way create context object , pass context object along b , c instead of passing a. context object plays role our wrapper. context object becomes more useful if multiple variables needs shared between them (the shared/global state) - see "context pattern". example:
public class context { public a; public ...other state want share...; public context(a a) { this.a = a; ... } } ... a = new a(); context context = new context(a,...); b b = new b(context); c c = new c(context);
depending on situation, static variable might fine, however. (or singleton)
(in cases passing a-instance along methods of b , c, rather constructor, might better - current version of (and might more thread-safe))
Comments
Post a Comment