implement a singleton design pattern as a template

Here is the question:

Implement a singleton design pattern as a template such that, for any given class Foo, you can call Singleton::instance() and get a pointer to an instance of a singleton of type Foo. Assume the existence of a class Lock which has acquire() and release() methods. How could you make your implementation thread safe and exception safe?

My analysis:

as Joshua Bloch points out in "effective java", the better ways to implement a singleton class is enum and public static factory method. Combining volatile and synchronized is the way I know to make it thread safe and lazy initialization as follows

public class myS{
  private static volatile final _ins = null;
  private myS(){};
  public static myS getIns(){
    synchronized(){
      if(_ins==null) _ins = new myS();
    }
    return _ins;
  }
}  

At this moment, I am a little confused to make a singleton template. My understanding is that we either have an interface with generic type or an abstract class. As long as the clients implement them, they are singleton. So, my guess solution is as follows:

public interface singleton<T>{
    public T instance();
}

public class Foo implements singleton<T>{
    private static volatile final Foo _ins = null;     

    public static Foo instance(){
        synchronized(this)         
             if(_ins==null){
                _ins = new Foo();
             }
        }
    }
}

The easiest way to get singleton functionality is to use a Dependancy Injection (DI) framework like Spring. There are plenty of other benefits gained by using DI as well.


'singleton' does not fit with 'template'. It is a kind of contradiction. If think you will be better off implementing enums as following

public enum MySingleton1 {

    ;

    public static void MethodA() { ... };

}

public enum MySingleton2 {

    ;

    public static int MethodB() { ... };

}

EDIT

A solution without enums would be:

public interface singletonMarker{};

public final class MySingleton1() extends singletonMarker {

    public static final MySingleton1 INSTANCE = new MySingleton1();

    private MySingleton1() {};

    public synchronized int mySyncMethod() { ... };

}

Usage

MySingleton1.INSTANCE.mySyncMethod();

The interface is only acting as marker, but it is not really necessary.

链接地址: http://www.djcxy.com/p/64254.html

上一篇: Android:SQLite(ORMLite)事务隔离级别

下一篇: 实现单身设计模式作为模板