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();//通过调用方法获取唯一对象。
    

    注意事项

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

  • 相关阅读:
    tp文件上传
    tp5与页面链接
    tp5语法查询
    tp5基本增删改查
    tp5基本登录
    数据修改
    文件上传。判断。一维二维数组
    数据库连接
    php针对于数据库的改变
    php数据库连接
  • 原文地址:https://www.cnblogs.com/tigo/p/14297964.html
Copyright © 2011-2022 走看看