LeT*_*Tex 3 java singleton spring design-patterns
我有一个单例类,必须使用接口将它作为服务公开给其他应用程序。
例如:
public class MySingleSingletonClass{
private static final MySingleSingletonClass THIS_INSTANCE = new MySingleSingletonClass();
private MySingleSingletonClass() {}
public static MySingleSingletonClass getInstance(){
return THIS_INSTANCE;
}
//do other staff
public int methodA(){
//some service
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我想通过接口公开此类的所有服务,这是我的第一次尝试:
public interface MyServiceInterface{
int methodA();
MyServiceInterface getInstanceThroughService();
}
Run Code Online (Sandbox Code Playgroud)
当MySingleSingletonClass实现此接口时:
public class MySingleSingletonClass implements MyServiceInterface{
private static final MySingleSingletonClass THIS_INSTANCE = new MySingleSingletonClass();
private MySingleSingletonClass() {}
public static MySingleSingletonClass getInstance(){
return THIS_INSTANCE;
}
@Override
public int methodA(){
//some service
}
@Override
MyServiceInterface getInstanceThroughService(){
return MySingleSingletonClass.getInstance();
}
}
Run Code Online (Sandbox Code Playgroud)
我看到这种实施有两个问题,
首先,如果我使用像spring这样的框架,并且尝试获取MyServiceInterface类型的bean,那么如何实例化该类?我读到Spring仍会使用反射来调用该类的私有承包商。这个实例还会是单例吗?
其次,如果Spring已经为我提供了实例,我看不出使用实例本身调用getInstanceThroughService()方法的意义。感觉此实现存在问题。
谢谢
默认情况下,典型的春豆是单例!
@Service
public class MySingleSingletonClass{
public int methodA(){...}
}
@Service
public class ConsumerA{
@Autowired
private MySingleSingletonClass mssc;
}
@Service
public class ConsumerB{
@Autowired
private MySingleSingletonClass mssc;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您将有3个bean:-一个MySingleSingletonClass-一个ConsumerA-一个ConsumerB
参考mssc
中ConsumerA
和ConsumerB
将指向同一个实例MySingleSingletonClass
。
因此,您无需实现标准的Singleton模式,Spring会为您完成。
归档时间: |
|
查看次数: |
764 次 |
最近记录: |