• 单例模式


    单例模式的要点有三个;一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。我现在用的系统中的上传平台的类就是一个单例模式,最近看了些资料才知道的一些好处:1.实例控制:Singleton 会阻止其他对象实例化其自己的 Singleton 对象的副本,从而确保所有对象都访问唯一实例;2.灵活性:因为类控制了实例化过程,所以类可以更加灵活修改实例化过程。使用单例模式的时机是当实例存在多个会引起程序逻辑错误的时候。比如类似有序的号码生成器这样的东西。

    单例模式的两种模式:

    饿汉式:

    public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton(){
     
    }
    public static Singleton getInstance(){
    return instance;
    }
    }
    懒汉式:
    public class Singleton {
    private static Singleton instance = null;
    private Singleton(){
    }
    public static Singleton getInstance(){
    if(instance==null){
    synchornized(Singleton.class){
    if(null == instance){
    instance = new Singleton();
    }
    }
    }
    return instance;
    }
    }
  • 相关阅读:
    1226 倒水问题
    1230 元素查找
    2152 滑雪
    1099 字串变换 2002年NOIP全国联赛提高组
    3027 线段覆盖 2
    P2066 机器分配
    spring的作用及优势---第一个spring示例
    密码框显示提示文字
    紫薇~还记得大明湖畔的HTML5智力拼图吗?
    细说javascript函数
  • 原文地址:https://www.cnblogs.com/hdsbk/p/2863100.html
Copyright © 2020-2023  润新知