Singleton
Key Point:
1. Only one instance for the singleton type class.
2. All values stored in the singleton will be accessible from everywhere.—Shared
public class MySingleton {
private int myNumber;
private static MySingleton instance;
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
// 将构造方法设定为私有,从而保证智能内部调用,从而反馈到 getInstance(), 从而保证只能存在一个实例被实现。
private MySingleton() {}
public void setMyNumber(int myNumber) {
this.myNumber = myNumber;
}
public int getMyNumber() {
return myNumber;
}
}
public class A {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
mySingleton.setMyNumber(42);
/*...*/
}
public class B {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
int number = mySingleton.getMyNumber();//which will be 42
/*...*/
}
Static
The key Point:
1. The advantage of A static class is to use it without having to create an object
Reference:http://stackoverflow.com/questions/24214148/java-getinstance-vs-static