• java设计模式值单例模式


    1.单例模式

     应用场合:有些对象只需要一个就够了,如古代的皇帝,老婆

     作用:保证整个应用程序中某个实例有且只有一个

     类型:饿汉模式,懒汉模式

    (1)饿汉模式

         package com.xiaolin;

         public class Singleton{

              //将构造方法私有化,不允许外部直接创建对象

             private   Singleton(){

             }

             //创建类的唯一实例,试用private,static 修饰

        private static Singleton instance = new Singleton(); 

       //提供一个获取静态实例的方法,使用public static 修饰

             public static Singleton getInstance(){

           return instance;

            }

        }

    (2)懒汉模式

          

     package com.xiaolin;

         public class Singleton2{

              //将构造方法私有化,不允许外部直接创建对象

             private  Singleton2(){

             }

             //声明类的唯一实例,试用private,static 修饰

        private static Singleton2 instance;

       //提供一个获取静态实例的方法,使用public static 修饰

             public static Singleton2 getInstance(){

                  if(instance == null){

                      return new Singleton2();

                 }        

         return instance;     

            }

        }

     (3)测试类

         public  class Test {

             public static void main(String[] args){

                  //饿汉模式

                   Singleton instance1 = Singleton.getInstance();

                   Singleton instance2 = Singleton.getInstance();

                   System.out.println(instance1 == instance2);

                                Singleton instance3= Singleton2.getInstance();

                                Singleton instance4 = Singleton2.getInstance();

                                System.out.println(instance3==instance4);      

                //懒汉模式

                

                   

            }

        }

     (4)测试结果

       instance1与instance2属于同一实例

       instance3与instance4属于同一实例

    2.饿汉模式与懒汉模式的区别

       (1)饿汉模式的特点是加载类时比较慢,因为需要创建对象,但运行时获取对象比较快,线程安全

       (2)懒汉模式的特点是加载类时比较块,但运行时获取对象比较慢,线程不安全

       

     

  • 相关阅读:
    ECSHOP给分类添加图
    windows2008一键安装环境的配置说明
    在css中定义滚动条样式
    登录不到phpmyadmin
    dedecms程序给栏目增加缩略图的方法
    httpd.conf
    关于 equals() 与 hashCode() 个人理解总结
    postman 安装失败 Failed to install the .NET Framework, try installingthe latest version manully
    docker 私有仓库The push refers to repository [x:5000/test] Get https://x:5000/v2/: dial tcp x:5000: conn
    Redis window 和 Linux 环境下的搭建
  • 原文地址:https://www.cnblogs.com/xiaolin-peter/p/6956590.html
Copyright © 2020-2023  润新知