java 工厂 单例,java – 创建一个返回单例的工厂

我想你需要的是

Multiton pattern.

The multiton pattern is a design pattern similar to the singleton,

which allows only one

instance of a class to be created. The multiton pattern expands on the

singleton concept to manage a map of named instances as key-value

pairs. Rather than have a single instance per application (e.g. the

java.lang.Runtime object in the Java programming language) the

multiton pattern instead ensures a single instance per key.

public class FooMultiton {

private static final Map instances = new HashMap();

private FooMultiton() {

// no explicit implementation

}

public static synchronized FooMultiton getInstance(Object key) {

// Our "per key" singleton

FooMultiton instance = instances.get(key);

if (instance == null) {

// Lazily create instance

instance = new FooMultiton();

// Add it to map

instances.put(key, instance);

}

return instance;

}

// other fields and methods ...

}

The controllers have common code and since I don’t need to create

multiple instances of these controller, I think they should be

singletons.

您需要单个实例并不一定意味着您需要Singleton模式.您可以拥有一个实例,并在后续调用时传递该实例.不一定使用私有构造函数强制执行单一性.

另请阅读Evil Singletons,了解更多关于单身人士的不足之处.看完之后,如果你仍然觉得你需要Singleton,那就去吧.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值