单例模式和工厂模式的区别 [英] Difference between singleton and factory pattern

查看:48
本文介绍了单例模式和工厂模式的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是设计模式的新手,我真的看不出这两种模式之间的区别,它们都是创建模式,不是吗?每个模式的目的是什么?谢谢.

I'm new to design patterns and I cant really see a difference between this two patterns, both are creational patterns arent they? and what is the purpose of each pattern? thanks.

推荐答案

单例模式确保你总是返回相同的任何类型的实例,而工厂模式通常给你每种类型的不同实例.

A singleton pattern ensures that you always get back the same instance of whatever type you are retrieving, whereas the factory pattern generally gives you a different instance of each type.

单例的目的是让所有调用都经过同一个实例.一个例子可能是一个管理磁盘缓存的类,或者从静态字典中获取数据;在重要的地方,只有一个已知实例与资源交互.这确实降低了它的可扩展性.

The purpose of the singleton is where you want all calls to go through the same instance. An example of this might be a class that manages a disk cache, or gets data from a static dictionary; wherever it is important only one known instance interacts with the resource. This does make it less scalable.

工厂的目的是创建和返回新的实例.通常,这些实际上根本不是相同的类型,但它们将是相同基类的实现.但是,每种类型可能有很多实例

The purpose of the factory is to create and return new instances. Often, these won't actually be the same type at all, but they will be implementations of the same base class. However, there may be many instances of each type

这篇关于单例模式和工厂模式的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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