zoukankan      html  css  js  c++  java
  • java学习 类和对象12 单例子模式

    内容

    (在编程过程中的一些需要下的解决方法,非语法)有些情况下类所需的实例化对象只需要一个。

    基本知识

    单例子有其中,只学习最常见的两种。

    1. 首先将构造方法私有化>>使得其他类无法进行访问。
    2. 静态属性指向实例(饿汉式)/指向null(暂时)(懒汉式)
    3. public static的 getInstance方法,返回第二步的静态属性>>提供给其他类的访问方式
    public class GiantDragon{
        private GiantDragon{  //1
            
        }
        private static GiantDragon insltance= new GianDragon();//2
        
        public static GiantDragon getInstance(){
            return instance;
        }
    }
    
    public class GiantDragon{
        private GiantDragon(){//1
            }
    	private static GiantDragon insltance;//2
        public static GiantDragon getInstance(){
            if(null==instance){
                instance = new GiantDragon();
            }
            return instance;
        }
    }
    
    GiantDragon g1 = GiantDragon.getInstance();//通过调用方法获取唯一对象。
    

    注意事项

    懒汉式和饿汉式的区别就在于是否在启动时就实例化对象,为一种取舍。

  • 相关阅读:
    nginx常用配置
    docker 启动常用容器命令
    win10 安装 docker
    Selenium IDE for Google Chrome
    Python use goto statement
    TCP:一个悲伤的故事
    gtx770测评
    三十而立——年终总结
    bilibili自定义调整视频播放速度
    linux-安装docker
  • 原文地址:https://www.cnblogs.com/tigo/p/14297964.html
Copyright © 2011-2022 走看看