0

I have existing design of sort of "singleton" implementation with static constructor. I want to be able to destroy and recreate new instance.

Can this be done without changing the base design?

This is simplified prototype:

public static void main(String[] args) { ClassA.doWork(); ClassA.destruct(); ClassA.doWork(); // <--I need new instance here } public class ClassA { private static ClassA inst = new ClassA(); protected ClassA() { //init } public static void doWork(){ //do work } public static void destruct(){ inst = null; } } 
4
  • You might do the inst = new ClassA() in your doWork() method if you need a new instance EVERYTIME you call that method. Commented Feb 4, 2013 at 11:09
  • 2
    Can this be done without changing the base design? Probably. Should I keep the base design? Probably not. Commented Feb 4, 2013 at 11:11
  • not every time, only when the instance is explicitly destroyed Commented Feb 4, 2013 at 11:13
  • @assylias, I agree but this is the case. Commented Feb 4, 2013 at 11:14

4 Answers 4

3

If you're determined to go down this route, and don't like the null checks on every method, you could change your "destruct" approach to "reset":

 public static void reset(){ inst = new ClassA(); } 

Call that instead of destruct.

But, seriously, don't do it... spend time now to refactor this mess or it'll come back to bite you!

Sign up to request clarification or add additional context in comments.

Comments

0

Add following code to doWork Method:

public static void doWork() { if(inst == null) { inst = new ClassA(); } //do work } 

OR

Add a separate method to create instance, (similar to how you have to destory)

public static ClassA init() { if(inst == null) { inst = new ClassA(); } return inst; } 

2 Comments

the problem with that, that I have more then one doWork() methods, i will have to add this section to every one of them.
then use the separate method init to create instance.
0

The method doWork should check against null instances and either throw an IllegalStateException or create a new instance of ClassA and then do the logic:

 public static void doWork(){ if (inst == null){ // throw new IllegalStateException("instance has been destroyed"); // or inst = new ClassA(); } // doWork now } 

Comments

0

Create an instance in the doWork method like:

 private static ClassA inst; public static void doWork() { if (inst == null) { inst = new ClassA(); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.