关于java:Java设计模式一单例模式

5次阅读

共计 2144 个字符,预计需要花费 6 分钟才能阅读完成。

package com.nasuf.pattern.singleton;

/**
 * 单例模式
 */
public class Test {public static void main(String[] args) {Singleton1 singleton1 = Singleton1.getInstance();
        Singleton1 singleton2 = Singleton1.getInstance();
        System.out.println(singleton1 == singleton2);   // true
        System.out.println(singleton1.hashCode());  // 621009875
        System.out.println(singleton2.hashCode());  // 621009875
    }
}

/**
 * 饿汉式一
 * 长处:简略,在类加载时实现实例化,防止了线程同步问题
 * 毛病:在类加载时实现实例化,没有达到懒加载成果,如果从未应用过这个实例,则会造成内存节约
 */
class Singleton1 {private Singleton1() { }

    private final static Singleton1 instance = new Singleton1();

    public static Singleton1 getInstance() {return instance;}
}

/**
 * 饿汉式二
 * 长处:简略,在类加载时实现实例化,防止了线程同步问题
 * 毛病:在类加载时实现实例化,没有达到懒加载成果,如果从未应用过这个实例,则会造成内存节约
 */
class Singleton2 {private Singleton2() { }

    private static Singleton2 instance;

    static {instance = new Singleton2();
    }

    public static Singleton2 getInstance() {return instance;}
}

/**
 * 懒汉式一
 * 长处:懒加载成果
 * 毛病:线程不平安,只能利用在单线程状况下
 */
class Singleton3 {private Singleton3() { }

    private static Singleton3 instance;

    public static Singleton3 getInstance() {if (instance == null) {instance = new Singleton3();
        }
        return instance;
    }
}

/**
 * 懒汉式二
 * 长处:懒加载成果,线程平安
 * 毛病:效率低,每个线程在想取得类的实例时,执行 getInstance 办法都要进行同步
 */
class Singleton4 {private Singleton4() { }

    private static Singleton4 instance;

    public static synchronized Singleton4 getInstance() {if (instance == null) {instance = new Singleton4();
        }
        return instance;
    }
}

/**
 * 懒汉式三
 * 毛病:线程不平安,效率低,每个线程在想取得类的实例时,执行 getInstance 办法都要进行同步
 */
class Singleton5 {private Singleton5() { }

    private static Singleton5 instance;

    public static Singleton5 getInstance() {if (instance == null) {synchronized (Singleton5.class) {instance = new Singleton5();
            }
        }
        return instance;
    }
}

/**
 * 双重查看(举荐应用)*/
class Singleton6 {private Singleton6() { }

    private static volatile Singleton6 instance;

    public static Singleton6 getInstance() {if (instance == null) {synchronized (Singleton6.class) {if (instance == null) {instance = new Singleton6();
                }
            }
        }
        return instance;
    }
}

/**
 * 动态外部类(举荐应用)* 外部类装载时,动态外部类不会被装载;外部类只会被装载一次,在类进行初始化时,其余线程无奈进入
 * 保障了线程平安;*/

class Singleton7 {private Singleton7() { }

    private static class SingletonInstance {private static final Singleton7 INSTANCE = new Singleton7();
    }

    public static synchronized Singleton7 getInstance() {return SingletonInstance.INSTANCE;}
}

/**
 * 枚举(举荐应用)* 线程平安,避免反序列化从新创立新的对象
 * 应用:Singleton8 instance = Singleton.INSTANCE
 */

enum Singleton8 {INSTANCE;}
正文完
 0