zoukankan      html  css  js  c++  java
  • 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)懒汉模式的特点是加载类时比较块,但运行时获取对象比较慢,线程不安全

       

     

  • 相关阅读:
    mongodb06---索引
    mongodb05---游标
    mongo04---基本查询
    mysql06---权限控制
    mysql05---游标
    使用 inotifywait的方式监控文件夹发生变化后自动执行脚本的方法
    ubuntu18.04 安装wine以及添加mono和gecko打开简单.net应用的方法
    Android之Socket群组聊天
    史上最完整的Android开发工具集合
    Android SurfaceView使用详解
  • 原文地址:https://www.cnblogs.com/xiaolin-peter/p/6956590.html
Copyright © 2011-2022 走看看