Search code examples
javaoopstatic-class

Static or new instance for every object?


I saw some piece of code looks like

public class A {

 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 We put C c var. (which is default for all objects of class A ) for every object of class A , we just use a lot of memory for large of objects of class A, maybe better to make C c static ? We will create only one instance of class C for whole class and use it to every object of class A . If we do so ,after that code will like like

public class A {
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 .


Solution

  • the answer to that question depends on the logic of the application and/or what A is supposed to do with the C instance. If just once instance of a particular object is required, I would suggest to use the Singleton pattern in Java https://en.wikipedia.org/wiki/Singleton_pattern .

    However, if an instance of class A is changing its C member, it would be a bad idea to use the above-mentioned approach, because by changing the C member on one A object, you could interfere the computation that is done with, or on another A object.

    If the C member contains configuration options or data that is used by all objects (as illustrated in the example above) and, hence, is not subject to change, You could use the singleton pattern to make it accessible for all A instances -- In my opinion that's fine.

    Best, Julian