0
我有3类:Core
,Cache
和HttpClient
保留周期,弱房地产
在Core
我初始化缓存,PARAM core
后,我通过Cache
实例HttpClient
。
Core.m
-(id)init {
self = [super init];
MyCache *cache = [[MyCache alloc] initWithCore:self];
self.httpClient = [[MyHttpClient alloc] initWithCache:cache];
}
Cache.m
@interface MyCache()
@property (nonatomic, strong) MyHttpClient *httpClient;
@end
@interface Core()
@property (nonatomic, strong) MyHttpClient *httpClient;
@end
@implementation MyCache
-(instancetype) initWithCore: (Core *)core
{
if (self = [self init]) {
self.httpClient = core.httpClient;
}
return self;
}
@end
-(void)foo
{
[self.httpClient doSomething];
}
MyHttpClient.m
@interface MyHttpClient : NSObject
@property (nonatomic, strong) MyCache *cache;
-(instancetype) initWithCache: (MyCache *)cache;
@end
@implementation MyHttpClient
-(instancetype) initWithCache: (MyCache *)cache
{
if (self = [self init]) {
self.cache = cache;
}
return self;
}
-(void) doSomething
{
[self.cache cacheSomething];
}
什么你可以看到,MyCache
通过依赖注入使用MyHttpClient
实例,另一方面MyHttpClient
实例使用MyCache
实例。
这是否叫做保留周期?
我是否需要设置MyCache
或MyHttpClient
属性为弱?
谢谢,
为什么缓存需要http客户端?我相信你真正的问题是你没有正确地分离关注点...... – Sulthan
@Sulthan Cache有我需要通过HttpClient发送到服务器的对象列表。在Httpclient发送完成后,我调用缓存来清除存储在列表中的对象 – snaggs
这正是我所说的,缓存不应该自己发送项目,它应该只保存它们。你的其他类中的一个应该询问“缓存”中的项目并发送它们。 – Sulthan