Special Singleton

I'm looking for a way to have 2 different getInstance() methods for a singleton class. The 2 methods should return 2 identical instances of that object, except a single method which should act in 2 different ways.

For example I have class MyObject, which has a getName() method. When you get an instance of the class using MyObject.getInstance(), it returns an instance whose getName() will return MyObject.name property. Instead when you use MyObject.getInstance(number), a call to getName() of the former instance will return id + name.

Thanks.

[566 byte] By [Tajallya] at [2007-10-2 15:25:06]
# 1

return 2 identical instances of that object, except a single method :)))

Singleton is a singleton because its getInstance() always returns a ref to the same instance, so you need another type of object. At the same time you need a class variable to keep an index which depends of getInstance parameter thus you'll have different objects. You can try following idea, it could partly help you.

class MyClass{

private static List<MyClass> listOfInstances = new ArrayList<MyClass>();

private MyClass(){

}

public static MyClass getInstance(int index){

// Check if the instance with such index already exists in the list

// otherwise create a new instance and put it into list to the certain place

// then returns it

}

public String getName(){

// find index of the instance inthe list and return it + Name

}

}

Cheers.

SashaPa at 2007-7-13 14:39:50 > top of Java-index,Other Topics,Patterns & OO Design...
# 2
I want to share the class data in both instances. They are really identical in data, so needless to make 2 different instances. A bad idea is to copy all props from one instance to the other.
Tajallya at 2007-7-13 14:39:50 > top of Java-index,Other Topics,Patterns & OO Design...
# 3
The good idea to keep references to the same instance in the list :)
SashaPa at 2007-7-13 14:39:50 > top of Java-index,Other Topics,Patterns & OO Design...
# 4
Oops err! I wanted to say that you need a place to keep an index anyway and also you need to bind it to the instance so may be you can create any kind of wrappers and keep them in the list and get the name through them.
SashaPa at 2007-7-13 14:39:50 > top of Java-index,Other Topics,Patterns & OO Design...
# 5
when singleton is not a singleton anymore http://www.javaworld.com/javaworld/jw-01-2001/jw-0112-singleton.html
kilyasa at 2007-7-13 14:39:50 > top of Java-index,Other Topics,Patterns & OO Design...
# 6
I would have rather gone with a combination of factory aned singleton in this case http://radio.weblogs.com/0122027/stories/2003/10/20/implementingTheSingletonPatternInJava.html
kilyasa at 2007-7-13 14:39:50 > top of Java-index,Other Topics,Patterns & OO Design...