首页 > 代码库 > 设计模式之单例模式的简单demo

设计模式之单例模式的简单demo

 1 /*
 2  * 设计模式之单例模式的简单demo
 3  */
 4 class Single
 5 {
 6     /*
 7      * 创建一个本类对象。
 8      * 和get/set方法思想一样,类不能直接调用对象
 9      * 所以用private限制权限
10      */
11     private static Single s = new Single();
12     /*
13      * 构造函数私有化目的是为了只能产生一个对象
14      */
15     private Single(){}
16     // 定义一个方法返回该对象,让外部可以调用。
17     public static Single getInstance()
18     {
19         return s;
20     }
21 }
22 
23 class  SingleDemo
24 {
25     public static void main(String[] args) 
26     {
27 //        Single s = Single.s;
28         Single s1 = Single.getInstance();
29         Single s2 = Single.getInstance();
30         System.out.println(s1 == s2);
31     }
32 }
/*
 * 单例模式之饿汉式与懒汉式
 */

 //饿汉式
class Single
{
    private static Single s = new Single();

    private Single(){}

    public static Single getInstance()
    {
        return s;
    }
}
//懒汉式
class Single 
{
    private static Single s = null;

    private Single(){}

    public static Single getInstance()
    {
        if (s == null)
        {
            s = new Single();
        }
        return s;
    }
}
 1 /*
 2  * 单例模式的小例子
 3  */
 4 class SuperMan
 5 {
 6     private String name;
 7 
 8     private static SuperMan man = new SuperMan("Clarke");
 9 
10     private SuperMan (String name)
11     {
12         this.name = name;
13     }
14 
15     public static SuperMan getInstance () 
16     {
17         return man;
18     }
19 
20     public void setName(String name)
21     {
22         this.name = name;
23     }
24     public String getName()
25     {
26         return this.name;
27     }
28 }
29 
30 class SuperManDemo 
31 {
32     public static void main(String[] args) 
33     {
34         SuperMan s1 = SuperMan.getInstance();
35         String name1 = s1.getName();
36         System.out.println("name1 = " + name1);
37 
38         SuperMan s2 = SuperMan.getInstance();
39         s2.setName("hero");
40         String name2 = s2.getName();
41         System.out.println("name2 = " + name2);
42     }
43 }

 

设计模式之单例模式的简单demo