| Author |
Switch between class implementation
|
Hamzah khammash
Greenhorn
Joined: Jan 05, 2012
Posts: 22
|
|
Hi,
i create an interface and made 3 implementations for this interface and i also use singleton class to insure that only one object will created and this object will show the implementation of class depending on the number entered by the user for example if user enter 1 the implementation of class 1 will show to user and so on , i try to do something like this
but i think i missed something and i dont know what is it .
so can anyone view my code and tell me if there anything wrong
Thanks
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
|
in the Singleton:getInstance() method do you assign any object value to the returning reference singleton?
|
 |
Hamzah khammash
Greenhorn
Joined: Jan 05, 2012
Posts: 22
|
|
|
In singleton.getInstance(String str) method i passed the value entered by the user to use it in the switch statement that create a object of another class and then return singleton of reference
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
The reference you return is the one referred by the singleton variable... So the below line shouldn't be assigning the singleton reference?
|
 |
Hamzah khammash
Greenhorn
Joined: Jan 05, 2012
Posts: 22
|
|
|
So how can i make a reference of class Test1 in this case ? Note that Test1 implements Testable interface and getInstance of type Testable also.
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
Did you try above code?
Can you post the code for Testable interface?
|
 |
Hamzah khammash
Greenhorn
Joined: Jan 05, 2012
Posts: 22
|
|
|
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
Hamzah khammash wrote:Note that Test1 implements Testable interface and getInstance of type Testable also.
What does getInstance mean here... a method? if so I see only Singleton class has it... any ways did you figure out the mistake?
|
 |
Hamzah khammash
Greenhorn
Joined: Jan 05, 2012
Posts: 22
|
|
|
getInstance() generate an instance if not exist and i think yes i figure my mistake using in switch statement and make singleton constructor protected
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
|
So why are you making the Singleton class to implement Testable interface when you do nothing with the methods exposed by them?
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
The Singleton implementation is bit flawed as it allows any number of instances to be created. I have modified it a to have one single instance.
If you need to refer different implementations at different times in your logic, then you should probably use a factory method to create instances based on user input and not Singleton.
|
 |
 |
|
|
subject: Switch between class implementation
|
|
|