今天看到这样一段代码不知其含义,小弟才疏学浅,不明其意,求大虾们指点
public class MapperInstances {
private static MapperInstances instance;
private MapperInstances() {}
public static MapperInstances getInstance() {
if(instance == null) {
instance = new MapperInstances();
}
return instance;
}
}
调用的语句为weka.core.Instances in = MapperInstances.getInstance().mapToWeka(data);
不知道为什么在class MapperInstances 类里还要设置 private static MapperInstances 的成员变量,这个变量有什么用谢谢大家java
public class MapperInstances {
private static MapperInstances instance;
private MapperInstances() {}
public static MapperInstances getInstance() {
if(instance == null) {
instance = new MapperInstances();
}
return instance;
}
}
调用的语句为weka.core.Instances in = MapperInstances.getInstance().mapToWeka(data);
不知道为什么在class MapperInstances 类里还要设置 private static MapperInstances 的成员变量,这个变量有什么用谢谢大家java
http://blog.csdn.net/huxiweng/article/details/8140338
第一种:
[java] view plaincopyprint?
01.public class Singleton2 {
02.
03. private Singleton2(){
04. System.out.println("This is Singleton2's instance.");
05. };
06.
07. private static Singleton2 instance = null;
08.
09. public static Singleton2 getInstance(){
10. if(instance == null) {
11. instance = new Singleton2();
12. }
13. return instance;
14. }
15.} 这种情况未加锁,可能会产生数据错误,比如两个同时新生成的对象,一个把对象数据改变了,而另一个使用的没改变之前的。
第二种:
[java] view plaincopyprint?
01.public class Singleton1 {
02.
03. private Singleton1(){
04. System.out.println("This is Singleton1's instance.");
05. }
06.
07. private static Singleton1 instance = null;
08.
09. public static Singleton1 getInstance2() {
10. if(instance == null){ //1
11. synchronized (Singleton1.class) { //2
12. if(instance == null) {
13. instance = new Singleton1();
14. }
15. }
16. }
17. return instance;
18. }
19.
20.} 这种只会在第一次的时候产生阻塞,之后每实例一次对象,就会在第1步时跳过去,在第一次实例的时候,会在第2步那里产生阻塞,以后就不会了,这种相对来说是最好的。
第三种:
[java] view plaincopyprint?
01.public class Singleton1 {
02.
03. private Singleton1(){
04. System.out.println("This is Singleton1's instance.");
05. }
06.
07. private static Singleton1 instance = null;
08.
09. public static synchronized Singleton1 getInstance(){ //1
10.
11. if(instance == null){
12. instance = new Singleton1();
13. }
14. return instance;
15. }
16.} 多线程的时候每次都会在1这里产生阻塞。
private static MapperInstances,定义这个全局变量有个好处就是,下面你调用getInstance() 时,如果已经创建了就不用继续创建了,否则如果你定义在方法里面就每用到一次就new一次
weka.core.Instances in = MapperInstances.getInstance().mapToWeka(data);
MapperInstances 没有显示weka.core.Instances 这个接口啊?
如果用了那个方法,只需这样写:
A a=A.getInstance();只用创建并初始化一次就行了
这么说吧,有些东西单例是很自然的。比如说现在为太阳系设计一个系统。
有个接口 叫 Planet(星球),有一个实现类叫Earth表示地球,地球只有一个,怎么办,用单例。这是从面相对象实践上说的。单纯从编程的角度出发,单例可以节省不必要的内存开销,屏蔽对象创建的复杂性,如果你知道spring并且知道bean默认是单例的,也许会有点感觉,为什么要这样。
下面只产生一个instance