首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为改造2制作一个单件?

如何为改造2制作一个单件?
EN

Stack Overflow用户
提问于 2017-01-16 16:46:45
回答 5查看 12.8K关注 0票数 4

如果存在多个改造调用,如何使改造单例,这样类中就不会有重复的代码,从而去掉不必要的代码。

EN

回答 5

Stack Overflow用户

发布于 2017-01-16 17:22:58

这里有一个例子,但是!虽然这可能是闪亮和易于使用的,但单例是邪恶的。如果可能的话,尽量避免使用它们。一种解决方法是使用依赖注入。

不管怎么说。

代码语言:javascript
运行
复制
public class Api {
    private static Api instance = null;
    public static final String BASE_URL = "your_base_url";

    // Keep your services here, build them in buildRetrofit method later
    private UserService userService;

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

        return instance;
    }

    // Build retrofit once when creating a single instance
    private Api() {
        // Implement a method to build your retrofit
        buildRetrofit(BASE_URL);
    }

    private void buildRetrofit() {
        Retrofit retrofit = ...

        // Build your services once
        this.userService = retrofit.create(UserService.class);
        ...
    }

    public UserService getUserService() {
        return this.userService;
    }
    ...
}

现在你已经把所有东西都放在一个地方了。使用它。

代码语言:javascript
运行
复制
UserService userService = Api.getInstance().getUserService();
票数 8
EN

Stack Overflow用户

发布于 2017-01-16 17:00:44

要实现单例类,最简单的方法是将类的构造函数设为私有。

  1. Eager initialization:

在急切初始化中,单例类的实例是在类加载时创建的,这是创建单例类的最简单的方法。

代码语言:javascript
运行
复制
public class SingletonClass {

private static volatile SingletonClass sSoleInstance = new SingletonClass();

    //private constructor.
    private SingletonClass(){}

    public static SingletonClass getInstance() {
        return sSoleInstance;
    }
}

懒惰的initialization:

此方法将检查是否已经创建了该类的任何实例?如果是,那么我们的方法(getInstance())将返回旧实例,如果不是,它将在JVM中创建单例类的新实例并返回该实例。这种方法被称为惰性初始化。

代码语言:javascript
运行
复制
public class SingletonClass {

    private static SingletonClass sSoleInstance;

    private SingletonClass(){}  //private constructor.

    public static SingletonClass getInstance(){
        if (sSoleInstance == null){ //if there is no instance available... create new one
            sSoleInstance = new SingletonClass();
        }

        return sSoleInstance;
   }
}

还有更多的东西,像Java反射API,线程安全和序列化安全单例。

有关单例对象创建的更多详细信息和深入理解,请查看此参考。

https://medium.com/@kevalpatel2106/digesting-singleton-design-pattern-in-java-5d434f4f322#.6gzisae2u

票数 1
EN

Stack Overflow用户

发布于 2017-01-17 11:09:35

代码语言:javascript
运行
复制
public class Singleton {
private volatile static Singleton singleton;
private Singleton(){}
public static Singleton getSingleton(){
    if (singleton == null) {
        synchronized (Singleton.class) {
            if (singleton == null) {
                singleton = new Singleton();
            }
        }
    }
    return singleton;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41672427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档