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

    顾名思义,单例模式就是要求只有一个实体对象。

    单例模式分为懒汉式和饿汉式

    饿汉式:一开始就创建对象,线程安全,但是如果用不到这个对象,会造成浪费

    懒汉式:要的时候才创建,不会造成浪费,但是会有线程安全的问题.

    饿汉式和懒汉式都是私有化构造函数,不让外面能够直接new 对象.

    饿汉式

    private static Hungry instance = new Hungry();
    
        private Hungry(){}
    
    
        public Hungry getInstance(){
            return instance;
        }

    懒汉不安全式

    public class LazyUnSafe {
    
        private LazyUnSafe instance;
    
        public LazyUnSafe getInstance(){
            if(instance == null){
                instance = new LazyUnSafe();
            }
            return instance;
        }
    }

    懒汉安全式

    public class LazySafe {
    
        private LazySafe instance;
    
        private LazySafe(){}
    
        public LazySafe getInstance() {
            if(instance == null){
                synchronized (LazySafe.class){
                    if(instance == null){
                        instance = new LazySafe();
                    }
                    return instance;
                }
            }
            return instance;
        }
    }
  • 相关阅读:
    第03组 Alpha冲刺(3/6)
    第03组 Alpha冲刺(2/6)
    第03组 Alpha冲刺(1/6)
    团队项目-选题报告
    第3组 团队展示
    福大软工 · BETA 版冲刺前准备(团队)
    Alpha 事后诸葛亮
    Alpha冲刺
    Alpha冲刺-(9/10)
    Alpha冲刺
  • 原文地址:https://www.cnblogs.com/lzh66/p/13301236.html
Copyright © 2011-2022 走看看