单例模式(Singleton Pattern)
这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
注意:
- 1、单例类只能有一个实例。
- 2、单例类必须自己创建自己的唯一实例。
- 3、单例类必须给所有其他对象提供这一实例。
使用场景:
- 1、要求生产唯一序列号。
- 2、WEB 中的计数器,不用每次刷新都在数据库里加一次,用单例先缓存起来。
- 3、创建的一个对象需要消耗的资源过多,比如 I/O 与数据库的连接等。
实现图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nT9kprVY-1635766870260)(C:\Users\19500\AppData\Roaming\Typora\typora-user-images\image-20211020222057422.png)]
懒汉式(线程安全的,加上了synchronized
):
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
懒汉式双检索
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
{
synchronized(Singleton.class){
if (instance == null){
instance=new Singleton();
}
}
}
return instance;
}
}
饿汉式:
public class Singleton {
private Singleton (){}
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
}