- 单例模式的应用场合:有些对象有且只有一个就够了。比如:我们的老婆(老公)。
- 作用:保证某些对象有且只有一个。
- 类型:
- 饿汉模式:加载类时速度慢,运行时速度快,线程安全
- 懒汉模式:加载类时速度快,运行时速度慢,线程不安全
- 实现:
- 构建方法私有化,不允许外界创建对象
- 创建类的唯一实例,使用private static修饰
- 提供一个用于获取实例的方法,使用public static修饰
- 代码实例
- package com.xzy.singleton;
- /*
- * 饿汉模式
- */
- public class Singleton {
- //1,构建方法私有化,不允许外部直接创建对象
- private Singleton(){
- }
- //2,创建类的唯一实例,使用private static修饰
- private static Singleton instance = new Singleton();
- //3,提供一个用于获取实例的方法,使用public static修饰
- public static Singleton getInstance(){
- return instance;
- }
- }
- package com.xzy.singleton;
- /*
- * 懒汉模式
- */
- public class Singleton2 {
- // 1,构建方法私有化,不允许外部直接创建对象
- private Singleton2() {
- }
- // 2,创建类的唯一实例,使用private static修饰
- private static Singleton2 instance;
- // 3,提供一个用于获取实例的方法,使用public static修饰
- public static Singleton2 getInstance() {
- if(instance==null){
- instance = new Singleton2();
- }
- return instance;
- }
- }
单例模式
最新推荐文章于 2024-08-18 22:13:14 发布