咱们来作一个很简单的小程序:在界面上随机显示10万朵小花,这些小花只有6种样式。如图所示:javascript
一看,这还不简单,直接建立10w个imageview显示不就是了,代码以下:java
- (void)viewDidLoad
{
[super viewDidLoad];
//使用普通模式
for (int i = 0; i < 100000; i++) {
@autoreleasepool {
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGFloat x = (arc4random() % (NSInteger)screenBounds.size.width);
CGFloat y = (arc4random() % (NSInteger)screenBounds.size.height);
NSInteger minSize = 10;
NSInteger maxSize = 50;
CGFloat size = (arc4random() % (maxSize - minSize + 1)) + minSize;
CGRect area = CGRectMake(x, y, size, size);
FlowerType flowerType = arc4random() % kTotalNumberOfFlowerTypes;
//新建对象
UIImageView *imageview = [self flowerViewWithType:flowerType];
imageview.frame = area;
[self.view addSubview:imageview];
}
}
}
- (UIImageView *)flowerViewWithType:(FlowerType)type
{
UIImageView *flowerView = nil;
UIImage *flowerImage;
switch (type)
{
case kAnemone:
flowerImage = [UIImage imageNamed:@"anemone.png"];
break;
case kCosmos:
flowerImage = [UIImage imageNamed:@"cosmos.png"];
break;
case kGerberas:
flowerImage = [UIImage imageNamed:@"gerberas.png"];
break;
case kHollyhock:
flowerImage = [UIImage imageNamed:@"hollyhock.png"];
break;
case kJasmine:
flowerImage = [UIImage imageNamed:@"jasmine.png"];
break;
case kZinnia:
flowerImage = [UIImage imageNamed:@"zinnia.png"];
break;
default:
break;
}
flowerView = [[UIImageView alloc]initWithImage:flowerImage];
return flowerView;
}复制代码
以为很好对吧?来,看看app占用的内存,如图:小程序
占用内存153M,这还不把人吓死,这才一个页面,要是再多来两个页面,那app还不直接把内存撑爆啊。后端
咱们使用instrument工具分析下,究竟是哪里占用了过多的内存。截图以下:设计模式
能够看到内存的消耗主要是调用方法[self flowerViewWithType:flowerType]
建立UIImageView致使的,进入这个方法再看看具体的内存分配,如图:数组
咱们知道UIImageview的建立是很消耗内存的,这一会儿建立10w个,内存占用可想而知。缓存
那怎么解决呢?app
分析知道,屏幕上的10W朵小花只有6种样式,只是在屏幕显示的位置不一样。那能不能只建立6个UIImageview显示小花,而后重复利用这些UIImageView呢?iview
答案是确定的,这就须要用到咱们要讲的设计模式:享元模式。下面具体看看dom
运用共享技术有效地支持大量细粒度的对象。
分析下上面的需求,咱们须要建立10w个uiimageview来显示小花,其实这些小花样式大多都是重复的,只是位置不一样,形成了内存浪费,解决方案就是缓存这些细粒度对象,让他们之建立一次,后续要使用直接从缓存中取就能够了。
可是要注意不是任何对象均可以缓存的,由于缓存的是对象的实例,实例存放的是属性,若是这些属性不断改变,那么缓存中的数据也必须跟着改变,那缓存就没有意义了。
因此咱们须要把一个对象分为两个部分:不变和改变的部分。把不变的部分缓存起来,咱们称之为内部状态,把改变的部分做为外部状态对外暴露,让外界去改变。对应到上面的程序,屏幕上显示的小花,图片自己是固定不变的(只有6种样式,其余都是重复),咱们能够把它做为内部状态分离出来共享,咱们称之为享元。而改变的是显示的位置,咱们能够把它做为外部状态让外界去改变,在须要的时候传递给享元使用。
为了方便让外界获取享元,通常采用享元工厂来管理享元对象,今天咱们只讨论共享享元,不共享实用意义不大,暂不作讨论。
要使用享元模式来实现上面的程序,关键之处就是分离出享元和外部状态,享元就是6种UIImagview,外部状态10W朵小花的位置。来看看具体的实现吧。
咱们须要分离出不变的部分做为享元,也就是6种UIImageview,因此咱们自定义一个flowerView
继承自系统的UIImageview,而后重写UIImageview的-- (void) drawRect:(CGRect)rect
方法,把参数rect
做为外部状态对外暴露,让外界传入uiimageviwe的frame来绘制图像。
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface FlowerView : UIImageView
{
}
- (void) drawRect:(CGRect)rect;
@end
==================
#import "FlowerView.h"
#import <UIKit/UIKit.h>
@implementation FlowerView
- (void) drawRect:(CGRect)rect
{
[self.image drawInRect:rect];
}
@end复制代码
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef enum
{
kAnemone,
kCosmos,
kGerberas,
kHollyhock,
kJasmine,
kZinnia,
kTotalNumberOfFlowerTypes
} FlowerType;
@interface FlowerFactory : NSObject
{
@private
NSMutableDictionary *flowerPool_;
}
- (UIImageView *) flowerViewWithType:(FlowerType)type;
@end
======================
#import "FlowerFactory.h"
#import "FlowerView.h"
@implementation FlowerFactory
- (UIImageView *)flowerViewWithType:(FlowerType)type
{
if (flowerPool_ == nil)
{
flowerPool_ = [[NSMutableDictionary alloc]
initWithCapacity:kTotalNumberOfFlowerTypes];
}
UIImageView *flowerView = [flowerPool_ objectForKey:[NSNumber
numberWithInt:type]];
if (flowerView == nil)
{
UIImage *flowerImage;
switch (type)
{
case kAnemone:
flowerImage = [UIImage imageNamed:@"anemone.png"];
break;
case kCosmos:
flowerImage = [UIImage imageNamed:@"cosmos.png"];
break;
case kGerberas:
flowerImage = [UIImage imageNamed:@"gerberas.png"];
break;
case kHollyhock:
flowerImage = [UIImage imageNamed:@"hollyhock.png"];
break;
case kJasmine:
flowerImage = [UIImage imageNamed:@"jasmine.png"];
break;
case kZinnia:
flowerImage = [UIImage imageNamed:@"zinnia.png"];
break;
default:
break;
}
flowerView = [[FlowerView alloc]
initWithImage:flowerImage];
[flowerPool_ setObject:flowerView
forKey:[NSNumber numberWithInt:type]];
}
return flowerView;
}
@end复制代码
咱们经过享元工厂随机取出一个享元,而后给它一个随机位置,存入字典。循环建立10w个对象,存入数组
#import "ViewController.h"
#import "FlowerFactory.h"
#import "FlyweightView.h"
#import <objc/runtime.h>
#import <malloc/malloc.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 使用享元模式
FlowerFactory *factory = [[FlowerFactory alloc] init];
NSMutableArray *flowerList = [[NSMutableArray alloc]
initWithCapacity:500];
for (int i = 0; i < 10000; ++i)
{
@autoreleasepool {
FlowerType flowerType = arc4random() % kTotalNumberOfFlowerTypes;
//重复利用对象
UIImageView *flowerView = [factory flowerViewWithType:flowerType];
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGFloat x = (arc4random() % (NSInteger)screenBounds.size.width);
CGFloat y = (arc4random() % (NSInteger)screenBounds.size.height);
NSInteger minSize = 10;
NSInteger maxSize = 50;
CGFloat size = (arc4random() % (maxSize - minSize + 1)) + minSize;
CGRect area = CGRectMake(x, y, size, size);
//新建对象
NSValue *key = [NSValue valueWithCGRect:area];
//新建对象
NSDictionary *dic = [NSDictionary dictionaryWithObject:flowerView forKey:key];
[flowerList addObject:dic];
}
}
FlyweightView *view = [[FlyweightView alloc]initWithFrame:self.view.bounds];
view.flowerList = flowerList;
self.view = view;
}
@end复制代码
取出享元对象,而后传入外部状态:位置,开始绘制UIImageview
#import <UIKit/UIKit.h>
@interface FlyweightView : UIView
@property (nonatomic, retain) NSArray *flowerList;
@end
==================
#import "FlyweightView.h"
#import "FlowerView.h"
@implementation FlyweightView
extern NSString *FlowerObjectKey, *FlowerLocationKey;
- (void)drawRect:(CGRect)rect
{
for (NSDictionary *dic in self.flowerList)
{
NSValue *key = (NSValue *)[dic allKeys][0];
FlowerView *flowerView = (FlowerView *)[dic allValues][0];
CGRect area = [key CGRectValue];
[flowerView drawRect:area];
}
}
@end复制代码
运行,再次查看app内存占用
看,只有44M,原来的三分之一都不到,你们能够本身试试,若是小花的数目再增长一倍,使用享元模式增长的内存才二十兆,可是若是使用咱们文章开头的方法,内存几乎是暴增2倍。如今认识到享元模式的威力了吧。
咱们再来看看此时的内存分配
注意上图中的UIImageview的flowerView内存占用才457KB,咱们进入建立UIImageview的工厂方法看看具体的内存分配
并且无论小花的数量增长多少,建立UIImageview的消耗内存都是这么多,不会增长太多,由于咱们只建立了6个UIImageview,而不是以前的几十万个。
对比此处的两张截图和文字开头的两种截图,能够看到差异。
你们一看到这里,享元模式太节省内存了,之后只要是须要建立多个类似的对象,均可以使用享元模式了。其实否则,咱们来看看,咱们分别使用两种方式建立100、1000、5000、10000个小花,而后看看内存消耗。你会发现只有当建立的小花数目达到10000左右,享元模式的内存消耗才比普通模式的内存消耗少,其余三种状况,普通模式的内存消耗居然比享元模式的内存消耗更低。
这是为何呢?
咱们再把这段代码拿出来看看
FlowerType flowerType = arc4random() % kTotalNumberOfFlowerTypes;
//一、重复利用对象
UIImageView *flowerView = [factory flowerViewWithType:flowerType];
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGFloat x = (arc4random() % (NSInteger)screenBounds.size.width);
CGFloat y = (arc4random() % (NSInteger)screenBounds.size.height);
NSInteger minSize = 10;
NSInteger maxSize = 50;
CGFloat size = (arc4random() % (maxSize - minSize + 1)) + minSize;
CGRect area = CGRectMake(x, y, size, size);
//二、新建对象
NSValue *key = [NSValue valueWithCGRect:area];
//三、新建对象
NSDictionary *dic = [NSDictionary dictionaryWithObject:flowerView forKey:key];
[flowerList addObject:dic];复制代码
能够发现咱们为了存储外部状态,在二、3两步咱们一共建立了两个新对象,这都是须要消耗内存的。
假设建立了1000个小花,使用享元模式,须要建立1000个NSValue和1000个NSDictonary对象以及6个UIImageview,而使用普通模式须要建立1000个UIImageview。虽然NSValue和NSDictonary对象占用的内存比UIImageview要小许多,可是一旦数量多起来,也是须要占用大量内存。
只有当小花数量达到必定的数量,这个时候建立NSValue和NSDictonary对象占用的内存比普通方式建立的UIImageview占用的内存小的时候,享元模式才有优点。
分析到这里你们应该知道,享元模式把原本的对象拆成两个部分:享元和外部状态。而每一个享元都须要一个与之对应的外部状态,而外部状态也是须要建立对象去存储的。因此只有当原本的对象占用的内存比存储外部状态的对象的占用内存大许多的时候,享元模式才有优点。
并且享元模式把原本简单的建立使用对象,拆分为几个类合做完成,操做更加复杂,这也是须要消耗内存和时间的。
综上所述,只有知足以下三个条件,才有必要考虑使用享元模式:
我翻阅大多数的书籍和网上文章,都只是给出了伪代码,而没有具体分析比较享元模式和普通模式在内存消耗方面的优劣,其实按照网上的那些代码,享元模式消耗的内存更多。
要找到知足上面要求,其实很是难,特别是移动端不多须要处理这么大量级的数据,毕竟设备能力有限。该模式在后端使用场景更加普遍。