user3280842
user3280842

Reputation: 79

Should I use one singleton for different purposes?

Ok, stackoverflow.
I've got to use singleton for database and for internet-processing. Is it a good practice to use one singleton for these (and have a mess in my singleton class) or two different singletons (and duplicate some singleton code).
Thanks in advance.

Upvotes: 0

Views: 43

Answers (2)

Ajit
Ajit

Reputation: 92

Yes you can create an enum say

    public ProcessManager{
     DB_PROCESS {    
                  public void process(){
                                ... specific code for db
                                commonCode();         
                                ..specific code for DB
                               }
                      }, 
     NETWORK_PROCESS{
                   public void process(){
                              ... specific code for network
                              commonCode();
                              ...specific code for network         
                               }
                     };

     public void process(){
     }

     public void commonCode(){

             ... common code
     }  
     }

How to call?

ProcessManager.DB_PROCESS .process(); ProcessManager.NETWORK_PROCESS.process();

Remember enums are the best way to implement a singleton class (effective-java-2nd-edition)

Upvotes: 0

antonio
antonio

Reputation: 18242

It's never a good approach to use the same class with two different purposes. Each class should have a unique responsibility (Single Responsibility Principle)

If you need to duplicate some code between classes, consider refactoring and creating a superclass for both classes (if classes can be siblings), or use some kind of helper class to perform the common operations.

Upvotes: 2

Related Questions