设计模式- 单例模式

最近在看一些深度学习的一些资料 由于大规模的模型训练对代码效率质量要求比较高最近在复习一些设计模式和算法的资料 我会保持每周一篇的节奏基本上就会讲算法和设计模式,写文章的同时加深一下自己的记忆,有错误之处望大家指正

什么是设计模式? 设计模式就是 自古空气多余恨,唯有套路得人心 设计模式就写代码的一种套路 就像我们中华武术的套路一样各个门派都有自己固定的套路,代码也一样不同的场景应用不同的代码套路,这些套路是大家总结出来公认比较好的一种代码编写思想(代码编写套路)

单例模式:他是一种设计模式,他的作用是让一个类只能拥有一个实例 不论你创建 调用了多少次 他还是只有一个实例

单例模式通用的有两种写法 一种叫做 饿汉模式 一种叫懒汉模式

饿汉式

    package singleCase;  
    /** 
     * 单例  饿汉模式 
     *     饿汉模式下  实例随着类的加载而创建 
     * @author admin 
     * 
     */  
    public class HungryManPattern {  
        //创建类的 唯一实例(注意是唯一实列)  private static 修饰  
        private static HungryManPattern singleCase = new HungryManPattern();  
        //将构造方法私有化 杜绝通过构造方法创建实例  
        private HungryManPattern(){  
        }  
        //提供一个获取实例(你也可以理解成对象)的方法  
        public static HungryManPattern getsingleCase(){  
              
            return singleCase;  
        }  
          
      
    }  

懒汉式

懒汉式

[java] view plain copy

    package singleCase;  
    /** 
     * 懒汉模式 
     * @author admin 
     * 
     */  
    public class lazyPattern {  
        //声明一个 lazyPattern 变量  
        private static lazyPattern singleCase;  
        //将构造方法私有化 杜绝通过构造方法创造实例  
        private lazyPattern(){  
              
        }  
        //提供公共方法访问实例  
        public static lazyPattern getsingleCase(){  
            //如果 singleCase 为空的时候我们为他创建一个实例  
            if(singleCase == null){  
                singleCase = new lazyPattern();           
            }         
            return singleCase;  
        }  
      
    }  
我们可以用一个测试类来看他是创建了几个实例 

    package singleCase;  
      
    public class sibgleCaseTest {  
          
        public static void main(String[] args) {  
               HungryManPattern t1 = HungryManPattern.getsingleCase();  
               HungryManPattern t2 = HungryManPattern.getsingleCase();  
               if(t1 == t2){  
                   System.out.println("饿汉式 只创建了一个实例 ");  
               }  
                 
               lazyPattern s1 = lazyPattern.getsingleCase();  
               lazyPattern ss2 = lazyPattern.getsingleCase();  
                 
               if(t1 == t2){  
                   System.out.println("懒汉式 只创建了一个实例 ");  
               }  
                 
                  
        }  
      
    }  

运行结果
《设计模式- 单例模式》

                          发现问题请联系我(小弟在这多谢指教)邮箱wavesape@126.com
                                            addPerson : hzb 2018-3-10 00:19:12


    原文作者:设计模式
    原文地址: https://segmentfault.com/a/1190000013638746
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞