0

In Java, I have two classes that each take values from a Singleton class but it seems to be changing values in the Singleton and I would just like a local copy. This is a shortened version of whats happening in my classes.

method.getName() should return "Abbey", as thats how it was created earlier

public class MethodFragment1 extends Fragment {

    private Method method = MethodLab.get(getActivity()).getMethod();

    method.setName("Test");
}

public class MethodFragment2 extends Fragment {

    private Method method = MethodLab.get(getActivity()).getMethod();

    System.out.println(method.getName());
}

The output is "Test"

Do both classes not get a local copy of the Method from the Singleton class MethodLab and if not how do I get a local copy?

Allan Macmillan
  • 1,481
  • 3
  • 18
  • 30

1 Answers1

1

Since it is singleton - it returns the same object for all callers. That's the whole point of singleton pattern - all callers get the same instance. If you want separate instance for each caller - just create new instance every time someone calls getMethod():

Method getMethod()
{
     return new Method();
}

Basically, it is not clear what are you trying to do.. Alternatively you can return separate instance of "Something which provides method" every time someone calls MethodLab.get(). Hard to say w/o seeing your class structure

EDIT: If you want to provide a copy of you object to callers, you can clone your MethodProvider (have no idea what your MethodLab.get() returns:) ). Please note, you need to push changes back when you done:

public class MethodLab
{
    private static MethodProvider provider = null;
    public static MethodProvider get()
    {
        //Not thread safe...
        if(provider == null)
        {
             provider = new MethodProvider();
             provider.getMethod().setName("Abby");
        }
        return provider.clone();
    } 

    public static set(MethodProvider newProvider)
    {
        provider = newProvider;
    }
}
Pavel Dudka
  • 20,754
  • 7
  • 70
  • 83
  • Should it not return then a local object that I can manipulate without pushing all changes back to the Singleton class? – Allan Macmillan Jan 07 '14 at 00:12
  • I really think you misunderstand Singleton pattern... With singleton all changes you make within local function, will be reflected on the main object. What you are operating with is just a pointer to the main object. Instance is only one – Pavel Dudka Jan 07 '14 at 00:16
  • Ahh okay, thank you. In that case, is there a way of getting a "local" copy? – Allan Macmillan Jan 07 '14 at 00:18
  • You need to `clone` your object (either before or after) you call `getMethod`. In this case your method needs to implement `Clonnable` interface. You need to push your changes back to singleton though – Pavel Dudka Jan 07 '14 at 00:21
  • Thanks man, solved it. Cloning did the trick, I misunderstood the Singleton concept – Allan Macmillan Jan 07 '14 at 01:01