Design patterns (a) - Singleton

Disclaimer: This article is a blogger original article, please indicate the source. Welcome to public concern number: Java Notes Share (xiaosen_javashare) https://blog.csdn.net/qq_36447151/article/details/87602801

Singleton

To ensure that only one instance of a particular class, and examples of their own and provide the instance of the whole system. Constructor privatization, it can not be new.

Item code: Github

Application of the singleton

advantage

  1. Only one instance in memory, reducing memory costs
  2. When generating an object requires more resources, such as reading configuration, dependency produce other objects, may be produced by a singleton object directly when the application starts, and then the permanent way to solve the memory-resident
  3. Singleton pattern to avoid multiple assignment of resources, such as file a written motion, since there is only one instance in memory, to avoid the same resource at the same time file write operations.
  4. Singleton pattern to avoid multiple assignment of resources, such as file a written motion, since there is only one instance in memory, to avoid the same resource at the same time file write operations.

Shortcoming

  1. Singleton interfaces generally do not expand very difficult;
  2. Singleton pattern of the test is negative. In a parallel development environment, if a single embodiment mode is not completed, is not available for testing, no interface can not use a virtual mock manner object.
  3. Singleton and single responsibility principle conflict.

Several single embodiment implemented:

1, hungry man mode

public class SingleDemo {
    private static SingleDemo instance = new SingleDemo();
    //私有化构造器
    private SingleDemo() {
        //防止其他通过反射调用构造方法,破解单例
        if (instance != null) {
            throw new RuntimeException();
        }
    }
    //对外提供统一的访问点
    public static SingleDemo getInstance() {
        return instance;
    }
}

advantage:

  • Initialize an instance of the class is loaded by the JVM time, to ensure the security thread
  • Simple convenient, high access efficiency

Disadvantages:

  • Can not be achieved lazy loading, resource utilization is not high

2, lazy mode

public class SingleDemo2 {
    // 此处并不初始化实例
    private static SingleDemo2 instance;

    private SingleDemo2() {
        if (instance != null) {
            throw new RuntimeException();
        }
    }
    /**
     * 当调用此方法的时候才初始化实例, 为了实现线程安全,需要使用同步方法
     */
    public static synchronized SingleDemo2 getInstance() {
        if (instance == null) {
            instance = new SingleDemo2();
        }
        return instance;
    }
}

advantage:

  • Only use this class when it is initialized instance, optimize resource utilization

Disadvantages:

  • In order to achieve thread-safe, use a synchronization method to get an increase of overhead access

3, double-checked

public class SingleDemo3 {
    private static SingleDemo3 instance;

    private SingleDemo3() {
        if (instance != null) {
            throw new RuntimeException();
        }
    }

    public static SingleDemo3 getInstance() {
        //第一重检查,提高效率
        if (instance == null) {
            synchronized (SingleDemo3.class) {
                //第二重检查保证线程安全
                if (instance == null) {
                    instance = new SingleDemo3();
                }
            }
        }
        return instance;
    }
}

advantage:

  • Implement lazy loading
  • Improve access efficiency by reducing the synchronization area and the first check

Disadvantages:

  • In order to achieve thread-safe, use a synchronization method to get an increase of overhead access

4, static inner classes

public class SingleDemo4 {
    private static SingleDemo4 instance;

    private static class SingleDemo4Holder {
        private static final SingleDemo4 instance = new SingleDemo4();
    }

    private SingleDemo4() {
        if (instance != null) {
            throw new RuntimeException();
        }
    }

    /**
     * 调用这个方法的时候,JVM才加载静态内部类,才初始化静态内部类的类变量。由于由JVM初始化,保证了线程安全性,
     * 同时又实现了懒加载
     */
    public static SingleDemo4 getInstance() {
        return SingleDemo4Holder.instance;
    }
}

advantage:

  • Namely to achieve a thread-safe, but also to achieve a lazy loading

Disadvantages:

  • Achieve slightly more complex

5, enumeration class

public enum SingleDemo5 {
     INSTANCE;
    public void someMethod(){
        
    }
}

advantage:

  • Simple
  • Thread Safety

Disadvantages:

  • Lazy loading can not be achieved

in conclusion

If you need lazy loading on the use of static inner class way, if you do not need to use enumerating

Extended Singleton pattern

If the class requires only produce a fixed number of instances.

public class SingleDemo6{
    // 最多可以生成的单例数量
    private static int maxNumberSingleDemo = 2;
    // 定义列表存放实例
    private static List<SingleDemo6> singleDemoList = new ArrayList<>();
    
    //生成对象
    static{
        for(int i=0; i<maxNumberSingleDemo; i++){
            singleDemoList.add(new SingleDemo6());
        }
    }
    
    private SingleDemo6(){}
    
    public static SingleDemo6 getInstance(){
        Random random = new Random();
        //随机调用一个实例
        int number = random.nextInt(maxNumberSingleDemo);
        return singleDemoList.get(number);
    }
    
}

This need to produce a fixed number of pattern objects called capped multi-mode embodiment, which is an extension of the single-mode embodiment, the use of multi-capped embodiment mode, in the design we can decide how many instances in memory, easy to expand the system, a single correction performance problem may exist embodiment, there is provided the system response speed. Such as reading a file, we can complete the work in a system is initially started a fixed number of reader instance in memory, then you can respond quickly when you need to read the file.


Welcome to public concern number:
No micro-channel public

Guess you like

Origin blog.csdn.net/qq_36447151/article/details/87602801