zoukankan      html  css  js  c++  java
  • 单例模式讲解

    网上搜到这个资料.

    加以修改加工一下,发布.感谢原作者的付出:http://singlewolf.javaeye.com/blog/173877

    Singleton类之所以是private型构造方法,就是为了防止其它类通过new来创建实例,即如此,那我们就必须用一个static的方法来创建一个实例(为什么要用static的方法?因为既然其它类不能通过new来创建实例,那么就无法获取其对象,那么只用有类的方法来获取了)

     1class Singleton {   
     2
     3     private static Singleton instance;  
     4
     5     private static String str="单例模式原版" ;
     6
     7 
     8
     9     private Singleton(){}   
    10
    11     public static Singleton getInstance(){   
    12
    13         if(instance==null){   
    14
    15             instance = new Singleton();   
    16
    17         }
       
    18
    19         return instance;   
    20
    21     }
       
    22
    23     public void say(){   
    24
    25         System.out.println(str);   
    26
    27     }
      
    28
    29     public void updatesay(String i){
    30
    31           this.str=i;
    32
    33           
    34
    35          
    36
    37     }
     
    38
    39}
       
    40
    41  
    42
    43public class danli{   
    44
    45    public static void main(String[] args) {   
    46
    47        Singleton s1 = Singleton.getInstance();   
    48
    49        //再次getInstance()的时候,instance已经被实例化了   
    50
    51        //所以不会再new,即s2指向刚初始化的实例   
    52
    53        Singleton s2 = Singleton.getInstance();   
    54
    55        System.out.println(s1==s2);   
    56
    57        s1.say();   
    58
    59        s2.say();   
    60
    61        //保证了Singleton的实例被引用的都是同一个,改变一个引用,则另外一个也会变.
    62
    63        //例如以下用s1修改一下say的内容
    64
    65        s1.updatesay("hey is me Senngr");   
    66
    67        s1.say();  
    68
    69        s2.say(); 
    70
    71        System.out.println(s1==s2); 
    72
    73    }
       
    74
    75}

    76

     打印结果:
    true

    单例模式原版

    单例模式原版

    hey is me Senngr

    hey is me Senngr

    true

    private static Singleton instance;
    public static Singleton getInstance()
    这2个是静态的 

    1.定义变量的时候是私有,静态的:private static Singleton instance;
    2.定义私有的构造方法,以防止其它类通过new来创建实例;
    3.定义静态的方法public static Singleton getInstance()来获取对象.instance = new Singleton();
  • 相关阅读:
    1123 Is It a Complete AVL Tree (30分)---如何建立平衡二叉搜索树(LL型RR型LR型RL型)+如何判断完全二叉树
    1021 Deepest Root (25 分)(经典搜索)
    PAT甲 1020 Tree Traversals (树的后序中序->层序)
    (数据结构)如何根据树的后序中序遍历求树的前序遍历
    习题2.3 数列求和-加强版 (模拟)
    PAT甲级 1051 Pop Sequence (25) && 2019天梯赛 L2-032 彩虹瓶 (25 分) (模拟+栈)
    PAT甲级 Are They Equal (25) (恶心模拟)
    PAT甲级1059 Prime Factors (25)(素数筛+求一个数的质因子)
    IO 模型
    Nginx 反向代理
  • 原文地址:https://www.cnblogs.com/redcoatjk/p/3562421.html
Copyright © 2011-2022 走看看