1

I was suggested to put my question here, so I'm doing so ;)

I need a common interface which represents some specific behavior:

public interface Contract(){
   public void methodA();
   public void methodB();
   // and so on...
}

The problem is, that in order to fulfill this behavior, implementation can be totally stateless - it can have a private constructor and expose only static methods:

public class MyUtilityClass /*implements Contract*/{
   private MyUtilityClass(){}
   public static void methodA(){
      // some implementation here...
   }
   public static void methodB(){
      // some implementation here...
   }
}

I have many such classes, with different behavior, so I want to refactor them and handle under a common interface.

Because I cannot implement Contract by means of static methods, is the only solution to convert MyUtilityClass to a singleton which implements the interface in order to achieve my goal? Or maybe would you suggest something else? For example Template method and Strategy which can by injected depending on a specific situation?

What would you propose?

radekEm
  • 367
  • 1
  • 3
  • 10
  • 1
    In the future if you feel that you have posted a question in the wrong place, then please flag for a moderator to migrate the question for you. Thank you. – maple_shaft Jan 29 '14 at 12:36

3 Answers3

2

it can have a private constructor and expose only static methods

Yes, it can, but there is no technical need for. So (besides some other good suggestions here) you should also consider the most simple solution for your problem, just to abandon the "static" keyword.

Doc Brown
  • 199,015
  • 33
  • 367
  • 565
  • 1
    Bingo. If these classes truly are stateless, then the specific instance you're using shouldn't matter. – MetaFight Jan 29 '14 at 12:38
1

Inside your utility class:

private static final Contract CONTRACT = new Contract() { // implement methods };

Now, you can wrap its methods or return that instance and use its methods directly, it's up to you.

EDIT: Another idea crossed my mind: Singletons can be created using enums too. And enums can implement interfaces!

Silviu Burcea
  • 618
  • 4
  • 13
1

The singleton is a creational pattern, and it's only about how many instances of a particular class exist, not about how they're used. By creating singletons you solve the problem of getting rid of the static methods, and thus you can introduce your common interface. That's the solution of your problem.

The moment all your classes implement a common interface you should refer to them using the abstraction. Then, you might if you want use a strategy pattern and exchange at runtime the particular implementation to be used. Strategy is a behavioral pattern, and in my opinion has nothing to do with your problem.

diegomtassis
  • 195
  • 1
  • 7