GOF 单例模式是否有任何可行的替代方案? [英] Are there any viable alternatives to the GOF Singleton Pattern?

查看:24
本文介绍了GOF 单例模式是否有任何可行的替代方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们面对现实吧.单例模式是极具争议的话题,成群结队的程序员 栅栏的两侧.有些人觉得 Singleton 只不过是一个美化的全局变量,还有一些人信奉模式并不断使用它.我不希望 单身争议成为核心然而,我的问题.每个人都可以进行拔河比赛,然后一决高下,看看谁赢了我所关心的.我想说的是,我不相信只有一个正确的答案,我也不是故意煽动党派争吵.当我问这个问题时,我只是对 singleton-alternatives 感兴趣:

Let's face it. The Singleton Pattern is highly controversial topic with hordes programmers on both sides of the fence. There are those who feel like the Singleton is nothing more then a glorified global variable, and others who swear by pattern and use it incessantly. I don't want the Singleton Controversy to lie at the heart of my question, however. Everyone can have a tug-of-war and battle it out and see who wins for all I care. What I'm trying to say is, I don't believe there is a single correct answer and I'm not intentionally trying inflame partisan bickering. I am simply interested in singleton-alternatives when I ask the question:

他们是否有任何特定的 GOF 单例模式替代品?

例如,在我过去多次使用单例模式时,我只是对保留一个或多个变量的状态/值感兴趣.但是,可以使用静态变量而不是使用单例模式在类的每次实例化之间保留变量的状态/值.

For example, many times when I have used the singleton pattern in the past, I am simply interested in preserving the state/values of one or several variables. The state/values of variables, however, can be preserved between each instantiation of the class using static variables instead of using the singleton pattern.

你还有什么想法?

我真的不希望这是另一篇关于如何正确使用单例"的帖子.同样,我正在寻找避免它的方法.为了好玩,好吗?我想我是在用你最好的电影预告片声音问一个纯粹的学术问题,在没有单身人士的平行宇宙中,我们能做什么?"

I don't really want this to be another post about "how to use the singleton correctly." Again, I'm looking for ways to avoid it. For fun, ok? I guess I'm asking a purely academic question in your best movie trailer voice, "In a parallel universe where there is no singleton, what could we do?"

推荐答案

Alex Miller in "我讨厌的模式" 引用以下内容:

Alex Miller in "Patterns I Hate" quotes the following:

当单身人士似乎是答案时,我发现通常更明智的做法是:

"When a singleton seems like the answer, I find it is often wiser to:

  1. 为单例创建一个接口和一个默认实现
  2. 在系统的顶部"构建默认实现的单个实例.这可能在 Spring 配置中,或在代码中,或根据您的系统以多种方式定义.
  3. 将单个实例传递给需要它的每个组件(依赖注入)

这篇关于GOF 单例模式是否有任何可行的替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆