Java singleton enum programmed to the interface?

Viewed 358

This is my first post on here so I will try to be precise. This is for a university project, we have to create a fish tank simulation on top of an OO architecture that we individually make. I'm exploring the uses of singletons and have found them quite useful, however reading online the way I currently implement it is not thread safe.

The way I currently implement it (Think its the lazy method) Note: We have to go through the interface

public interface myInterface
{
  void foo();
}

public class myClass implements myInterface
{
  private static myInterface instance;

  private myClass(){}

  private static myInterface Instance()
  {
     if(instance == null)
       instance = new myClass();

     return instance;
  }

  public void foo()
  {
    //Do stuff
  }

  public void bar()
  {
   //Do More Stuff
  }
}

This works well however its not thread safe I could add the synchronized keyword to the getter but I've read that that is quite heavy on the system and I have quite a few singletons.

private synchronized static myInterface Instance()
{
  if(instance == null)
    instance = new myClass();

  return instance;
} 

I have then moved on to an enum singleton which is thread safe and is not heavy on the system however I am unsure on how to program it to the interface.

public enum myClass implements myInterface
{
  INSTANCE;
  private myClass(){}

  public void foo()
  {
    //Do stuff
  }

  public void bar()
  {
   //Do More Stuff
  }
}

In programming to the interface I mean when I call the singleton I can only access methods that are in the interface (please correct me if I'm referring to this wrongly). This is where the way I have done the enum singleton fails. For example: With the lazy singleton I can not call this as its not in the interface:

 myClass.Instance().bar();

But it can call this which is correct, as it is in the interface.

myClass.Instance().foo();

With the enum however I can call this and its not programming to the interface

myClass.INSTANCE.bar();

I understand why its doing this as the class is an enum so it will be able to call everything in that enum class. So after this long post which I apologise for, the main question is: Can I make the enum version only call methods that are declared in the interface?

If it can't how heavy is a synchronized method on the system, I would have around 4-6 of them?

Please Note: Even though this is for a university project we are only running the simulation on one thread so it does not even need to be thread safe. I don't quite understand multi-threading but I thought it would be a good learning opportunity.

4 Answers
Related