zoukankan      html  css  js  c++  java
  • java设计模式之单例模式

    什么是单例

    • 保证类在内存中只有一个对象。
    • 对象是new出来的,因此也就是说在程序中只能new一次对象

    单例实现的基本步骤

    1》声明一个类,类中有一个静态属性,类型与类名相同     

    2》把空参构造方法声明为私有

    3》在类中提供一个公共静态访问方法来返回该对象实例

    单例的多种写法

    写法一 饿汉式

    class Singleton{

        private static Singleton instance = new Singleton();

        private Singleton(){}

        public static Singleton getInstance(){

           return instance;

        }

    }

    写法二 懒汉式

    class Singleton{

        private static Singleton instance;

       

        private Singleton(){}

       

        public static Singleton getInstance(){

           if(instance == null){

               instance = new Singleton();

           }

           return instance;

        }

    }

    写法三 另一种简单的写法 (饿汉式2.0)

    class Singleton{

        public static final Singleton instance = new Singleton();

        private Singleton(){}

    }

    饿汉式和懒汉式的区别

    • 饿汉式是空间换时间,懒汉式是时间换空间
    • 在多线程访问时,饿汉式不会创建多个对象,而懒汉式有可能会创建多个对象
    • 如果考虑线程安全问题,用饿汉式
    • 如果不考虑线程安全问题,用懒汉式
  • 相关阅读:
    ios原生项目内嵌u3d工程
    u3d内嵌H5游戏 设置cookie
    unity3d IL2CPP for android
    unity3D内嵌android项目
    Django 跨域问题
    tensorflow 调试tfdbg
    Cuda9.1+cunn7.1+Tensorflow1.7-GUP
    shader
    lua 中protobuf repeated 嵌套类 复合类型
    30岁的思考
  • 原文地址:https://www.cnblogs.com/ivan5277/p/10159674.html
Copyright © 2011-2022 走看看