关于设计模式之单例模式

简介

单例模式(singleton pattern),属于创建者模式的一种,主要用于面向对象编程中创建对象的一种模式。

单例类会负责创建自身的对象,并保证每次都是返回相同的对象。

本文博主通过常用的几种编程语言(JAVA、JS、Python)来实现各种单例模式。

应用场景

配置类: 当某个类需要提供系统相关配置,每次返回相同的实例。可以避免频繁的销毁创建配置类。

Java: J2EE 标 准 中 的 ServletContextServletContextConfig 等 、 Spring 框 架 应 用 中 的 ApplicationContext、数据库的连接池BDPool等也都是单例形式。Spring中Bean默认创建也是单例Bean,每个Ioc容器中只存在一个Bean的实例。

Python中的配置类,

线程池

实现方式

实现1:懒汉式 线程不安全

是否Lazy 初始化:是

是否线程安全: 否

最简单的单例模式实现方式。

/**
 * Java编程语言
 * 不支持多线程
 */
public class SingletonOne {
    private static SingletonOne instance;
    private SingletonOne(){}

    public static SingletonOne getInstance() {
        if (instance == null) {
            instance = new SingletonOne();
        }
        return instance;
    }
}
"""
    Python编程语言
    线程不安全
"""
class SimgleTonOne(object):

    def __new__(cls, *args, **kwargs):
        if not hasattr(SimgleTonOne, "_instance"):
            setattr(SimgleTonOne, "_instance", object.__new__(SimgleTonOne))

        return getattr(SimgleTonOne, "_instance")
/**
 * 懒汉式
 * @JS编程语言
 * @param {*} name 
 */
var SingletonOne = function (name) {
  this.name = name;
}

SingletonOne.instance = null;

SingletonOne.prototype.getName = function () {
  console.log(this.name)
}

SingletonOne.getInstance = function (name) {
  if (!this.instance) {
    this.instance = new SingletonOne(name);
  }
  return this.instance;
}

let a = SingletonOne.getInstance("xianren");
let b = SingletonOne.getInstance("xiaoliu");
console.log(a === b);
console.log(a.getName());

实现2:懒汉式 线程安全

/**
 * Java
 * 懒汉式单例
 * 线程安全
 */
public class LazySimgleSafe {
    private static LazySimgleSafe instance;

    LazySimgleSafe(){ }

    public static synchronized LazySimgleSafe getInstance() {
        if(instance == null){
            instance = new LazySimgleSafe();
        }
        return instance;
    }

    public static void main(String[] args) {
        LazySimgleSafe lazySimgleSafe1 = LazySimgleSafe.getInstance();
        LazySimgleSafe lazySimgleSafe2 =  LazySimgleSafe.getInstance();
        System.out.println(lazySimgleSafe1 == lazySimgleSafe2);
    }
}

实现3:饿汉式

是否Lazy 初始化:否

是否线程安全: 是

最常用的单例模式实现方式。容易产生垃圾对象,类装载的时候就实例化

/**
 * 饿汉式
 * @Java编程语言
 */
public class SingletonTwo{
    private static SingletonTwo instance = new SingletonTwo();
    private SingletonTwo(){}

    public static SingletonTwo getInstance() {
        return instance;
    }
}
"""
    python编程语言
    饿汉式
    程序开始运行时实例化类
"""
# Simgletontwo.py
class Simgletontwo(object):
    def __init__(self):
        pass

S = Simgletontwo()

# test.py
from Simgletontwo import S
/**
    JS语言
    饿汉式单例
*/
var hungrySingleton = (function () {
  var person = {
    name: "张三"
  }
  return function () {
    return {
      getInfo: function () {
        return person;
      }
    }
  }
})();

var personA = hungrySingleton();
var personB = hungrySingleton();
var personC = hungrySingleton();
var infoA = personA.getInfo();
var infoB = personB.getInfo();
var infoC = personC.getInfo();

console.log(infoA);
console.log(infoB);
console.log(infoC);
console.log(infoA === infoB, infoB === infoC);

infoA.name = "李四";
console.log(infoA);
console.log(infoB);
console.log(infoC);
console.log(infoA === infoB, infoB === infoC);

后续继续更新...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值