单例模式
UML
![单例模式](https://i-blog.csdnimg.cn/blog_migrate/1fb392d9f72b2575c6f491305fe07c46.png)
解释说明
- 单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
代码实现
package learn17;
public class Singleton1 {
private static Singleton1 instance;
private Singleton1() {
}
public static Singleton1 getInstance() {
if (null == instance) {
instance = new Singleton1();
}
return instance;
}
}
package learn17;
public class Singleton2 {
private static Singleton2 instance;
private Singleton2() {
}
public static Singleton2 getInstance() {
synchronized (Singleton2.class) {
if (null == instance) {
instance = new Singleton2();
}
return instance;
}
}
}
package learn17;
public class Singleton3 {
private static Singleton3 instance;
private Singleton3() {
}
public static Singleton3 getInstance() {
if (null == instance) {
synchronized (Singleton3.class) {
if (null == instance) {
instance = new Singleton3();
}
}
}
return instance;
}
}
package learn17;
public class Singleton4 {
private static final Singleton4 instance = new Singleton4();
private Singleton4() {
}
public static Singleton4 getInstance() {
return instance;
}
}
参考资料