Flyweight与Singleton模式之间的实际使用差异是甚么? [英] What are the practical use differences between Flyweight vs Singleton patterns?

查看:246
本文介绍了Flyweight与Singleton模式之间的实际使用差异是甚么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种模式似乎都是一样的。现实世界中的不同用例是什么?
谢谢

The two pattern seems to achieve the same thing. What are the different use cases in real world? Thanks

推荐答案

单身经常是可变的。这是不可能的一个flyweight。例如。一个flyweight可能代表一种颜色。如果您创建了一个红色,它是令人困惑的,而且它是绿色的,因为它的底层flyweight对象在代码中的其他地方更改为绿色。

A singleton is often mutable. That is not possible with a flyweight. E.g. a flyweight might represent a color. It would confusing if you created a red color and it was green instead because its underlying flyweight object was changed to green somewhere else in the code.

另外我会说一个单身是一种轻量级的子模式。你可以想到单个颜色对象是单身,但它们都是使用工厂选择正确的单例/ flyweight对象的系统的一部分。

Also I would say a singleton is sort of a subpattern of flyweight. You could think of individual color objects are singletons, but they are all part of a system where you use a factory to select the right singleton/flyweight object.

真的是很多关于戒严没有向API的用户呈现Flyweights,就像它们是独一无二的对象一样,单身是。

It is really a lot about preception. Flyweights are not presented to the user of the API as if they are unique objects, while singletons are.

可可(Objective-C)的示例:

Examples from Cocoa (Objective-C):

UIApplication.sharedApplication.statusBarHidden = YES

这显然是单个对象,您可以更改其状态。

This is obviously a single object and you can change its state.

UIColor *red = [UIColor redColor]

用户不需要知道红色是否为单例,因为它是不可变的。创建后不能更改颜色对象。因此,无论用户是单身人士还是创建新物品,都不会对用户产生实际的影响。因此,把这个称之为轻量级是有意义的。这是关于意图。

The user does not need to know whether red is a singleton or not because it is immutable. You can't change color objects after they are created. So it makes no practical difference to the user whether they are singletons or whether you create new objects. Thus it makes more sense to call this a flyweight. It is all about intention.

这篇关于Flyweight与Singleton模式之间的实际使用差异是甚么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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