2015-06-20 70 views
1

我在自由起诉辛格尔顿模式,我在想;什么时候够了,够了?这些都是我现在的单身人士。我并没有像所有人一样使用它们。我过度使用Singleton模式吗?

Database db = Database.getInstance(this); // wrapper for the library 
    Realm realm = Realm.getInstance(this); // library I use 
    AppUtils appUtils = AppUtils.getInstance(this); // app specific functions that manipulate database queries to produce targeted values 
    Utils utils = Utils.getInstance(); 
    Generator gen = Generator.getInstance(this); // necessary for the library 

我想也做这样的事情

AppFragments fr = AppFragments.getInstance(this, AttributeCommonInEveryActivity>)

或者我应该接口,并做BlerpActivity extends BlourpActivity

最后,以清除可能发生的影响你的意见的任何偏差。我知道,似乎我只使用一种设计模式,但我不是。我在考虑设计和实用方面工作^ _^

+1

如果'Database db'的确是“库的包装器”,那么你不需要'Realm realm',因为'db'应该包含'Realm'实例,并且如果有的话可以通过'db'获取它除了'db'需要它。关于你的其他三个单身人士,不知道他们做了什么,很难告诉你。尽管如此,为什么数据需要在全球范围内成为具体的具体原因。单身人士因为“打字很难”不是一个好的理由。 :-) – CommonsWare

+1

似乎你可以使用一个好的[DI](https://en.wikipedia.org/wiki/Dependency_injection)框架,例如[Guice](https://github.com/google/guice/wiki /动机)。这样,通过简单地[范围](https://github.com/google/guice/wiki/Scopes)适当地创建对象,就可以完全避免手写的JVM单例(一种反模式)。 –

+0

@CommonsWare 您好,非常感谢您的反馈。领域是图书馆,而不是我自己的建筑。这就是你与数据库沟通的方式(叫Realm/lame)。 这是我无法避免的唯一单例。数据库获取上下文并创建一个新的RealmInstance来获取常用结果。 你绝对正确的最后一句话。我尽量使它尽可能模块化 – MayTheSchwartzBeWithYou

回答

4

是的。是的,你是。但是我甚至在这之前,我认为你甚至不会使用单身模式

采取像Realm.getInstance(this)这样的方法,假设thisFooClass。如果Realm是单身人士,则只有一个它的实例永远存在。如果这是真的,那么为什么你必须通过this如果您通过不同的FooClass,结果会不同吗?

现在到了实际的问题 - 单身人士的烦恼已经涵盖了manybefore,所以我不会进入那个。相反,我会告诉你一个替代方法:依赖注入。

这里的单身您Realm类的版本(?):

class Realm { 
    private static final Realm instance = new Realm(); 

    public static Realm getInstance(FooClass foo) { 
     // black magic with foo 
     return instance; 
    } 
} 

// usage: 
Realm realm = Realm.getInstance(this); 

现在,这里的DI版本:

你告诉我哪一个看起来更短。

+0

你好。在不知道内部或Realm(https://realm.io/)的情况下,我认为他们使用类似'Realm.getInsance(context)'的东西来初始化上下文作为'this.context = context.getApplicationContext()',它是唯一的并坚持不懈。 所以只要你传递任何形式的'Context',它总会得到相同的结果。同样的事情适用于我的其他课程 – MayTheSchwartzBeWithYou