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

    java的单例设计模式包括:饿汉设计模式和懒汉设计模式;

    步骤: 1.创建一个对象把他设置为私有的成员变量,保证唯一

               2.私有构造方法,防止new一个对象。

               3.定义一个公开的静态方法,返回第一步创建的对象。

    饿汉单例设计模式:当类加载的时候会创建对象。

    class SingleDog{

          String name;

          int age;

          private static SingleDog s = new SingleDog(); //保证对象唯一,

    private SingleDog(){} // 私有构造方法,防止new创建

    public static SingleDog getInstance(){ //提供外部接口

               return s;

    }

    懒汉单例设计模式:用类创建对象的时候在创建

    class SingleDog {

          private static SingleDog s;  //声明本类的引用变量,不创建

          private SingleDog(){}; // 私有构造方法

          public static SingleDog getInstance(){ // 提供外部接口

               if(s == null){

                     s = new SingleDog();

    }

    return s;

    }

    }

  • 相关阅读:
    ABP 异常
    Vmware中安装的Ubuntu不能全屏问题解决
    centos7.4 文件权限
    webpack 入门(1)
    webpack(2) 概念
    centos7.4 rpm命令
    centos7.4 which、whereis、locate的使用
    centos7.4 find命令
    centos7.4 lsof用法
    centos7.4 用户和组的管理
  • 原文地址:https://www.cnblogs.com/z-jun/p/6076453.html
Copyright © 2011-2022 走看看