X.d 笔记

小Web,大世界

0%

设计模式(3):单例模式 Singleton

单例模式,最大使用,最大范围,什么,你的项目没用?功能主治:大量减小new运算,降低性能开销。

单例模式 Singleton

问题:

Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.

意图:

  • Separate the construction of a complex object from its representation so that the same construction process can create different representations.
  • Parse a complex representation, create one of several targets

代码

例1:实现1

package com.xdnote.DesignPattern.creational.signleton;

public class Singleton {
    /**
     * 私有构造器,防止被NEW
     * */
    private Singleton() {
        System.out.println("Build a Object");
    }

    public static Singleton obj = null;
    public static Singleton getInterface(){
        if(obj==null){
            obj = new Singleton();
        }
        return obj;
    }

    public void method(){
        System.out.println("Run Method");
    }
}

代码2:另一种实现

package com.xdnote.DesignPattern.creational.signleton;

public class Singleton2 {
    private Singleton2() {
        System.out.println("Build a Object");
    }

    private static class Provider {
        private static final Singleton2 obj =new Singleton2();
    }

    public static Singleton2 getInterface(){
        return Provider.obj;
    }
    public void method(){
        System.out.println("Run Method");
    }

}

代码3:客户端调用

package com.xdnote.DesignPattern.creational.signleton;

public class Client {

    /**
     * 超级简单的单例模式,这个也不用多说了,大家入门时都用过单例+工厂做过东西吧,这里提供了两种方法
     * @param args
     * 做用就不说了,看打出来的日志就知道,如果有多个地方需要一个对象时,可以减少new带来的性能损失
     */
    public static void main(String[] args) {
        //第一种是用常用的内部状态变量实现
        Singleton obj1 = Singleton.getInterface();
        obj1.method();
        Singleton obj2 = Singleton.getInterface();
        obj2.method();
        Singleton obj3 = Singleton.getInterface();
        obj3.method();

        //另一种用个内部静态类
        Singleton2 obj4 = Singleton2.getInterface();
        obj4.method();
        Singleton2 obj5 = Singleton2.getInterface();
        obj5.method();
        Singleton2 obj6 = Singleton2.getInterface();
        obj6.method();
    }

}

小结

单例模式 Singleton

  • 使用频率:极高

实在太多了,即可以单独使用,也可以配合在工厂或其它模式里面组合使用。可以说是只要程序中的一个对象不需要经常new或可以new之后就视为常量来使用时,就必须使用单例。

  • 利弊影响:极低

利:极度简单、省性能,只要在把new改为getInstance即可。

弊:比较小的情况下会出现数据异常,一般情况下比较好定位,但有些还是不好定位比如servlet.另外,菜鸟如果什么都用想着单例的话,可能会撑死内存。

  • 小评:
    简单实用,必备常识