Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

单例模式 #1

Open
FlowerBoot opened this issue Mar 19, 2020 · 3 comments
Open

单例模式 #1

FlowerBoot opened this issue Mar 19, 2020 · 3 comments

Comments

@FlowerBoot
Copy link
Owner

https://www.adoger.com/Singleton/

为了实现Singleton模式,我们有不同的方法,但是所有方法都具有以下共同概念。

私有构造函数,用于限制该类从其他类的实例化。
同一类的私有静态变量,是该类的唯一实例。
返回类实例的公共静态方法,这是外部世界获取单例类实例的全局访问点。

静态初始化

在静态的初始化中,在加载类时会创建Singleton类的实例,这是创建Singleton类的最简单方法,但是它存在一个缺点,即使客户端应用程序可能不使用它也会创建该实例。

package com.journaldev.singleton;


public class EagerInitializedSingleton {

private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}

public static EagerInitializedSingleton getInstance(){
    return instance;
} } ``` > 如果您的单例类没有使用大量资源,则可以使用这种方法。但是在大多数情况下,都是为文件系统,数据库连接等资源创建Singleton类的getInstance。除非客户端调用该方法,否则应避免实例化。另外,此方法不提供任何用于异常处理的选项。


静态块初始化
静态块初始化实现与热切初始化类似,不同的是,类的实例是在提供了异常处理选项的静态块中创建的。
package com.journaldev.singleton;

public class StaticBlockSingleton {

    private static StaticBlockSingleton instance;
    
    private StaticBlockSingleton(){}
    
    //static block initialization for exception handling
    static{
        try{
            instance = new StaticBlockSingleton();
        }catch(Exception e){
            throw new RuntimeException(
@FlowerBoot
Copy link
Owner Author

评论测试

@FlowerBoot
Copy link
Owner Author

nice

@FlowerBoot
Copy link
Owner Author

🔥

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant