java - Static or new instance for every object? -


i saw piece of code looks

public class {   public void dosomething(b b) {     b.addsometing("queue1", getdefault());     b.addsometing("queue2", getdefault());     b.addsometing("queue3", getdefault()); }  private c getdefault() {     c c = new c();     c.setautocreate(true);     c.setexired(false);     c.setdelay(3500);      return c; }} 

if put c c var. (which default objects of class ) every object of class a , use lot of memory large of objects of class a, maybe better make c c static ? create 1 instance of class c whole class , use every object of class a . if ,after code like

public class { private static c c = new c();  static {     c.setautocreate(true);     c.setexired(false);     c.setdelay(3500); }  public void dosomething(b b) {     b.addsometing("queue1", c);     b.addsometing("queue2", c);     b.addsometing("queue3", c); } 

}

i think it's better way , perhaps i'm wrong . please give me advise .

the answer question depends on logic of application and/or supposed c instance. if once instance of particular object required, suggest use singleton pattern in java https://en.wikipedia.org/wiki/singleton_pattern .

however, if instance of class changing c member, bad idea use above-mentioned approach, because changing c member on 1 object, interfere computation done with, or on object.

if c member contains configuration options or data used objects (as illustrated in example above) and, hence, not subject change, use singleton pattern make accessible instances -- in opinion that's fine.

best, julian


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -