美文网首页
结构型之七-享元模式

结构型之七-享元模式

作者: iOS_肖晨 | 来源:发表于2017-10-10 11:45 被阅读5次

    Flyweight(享元模式)

    运用共享技术有效地支持大量细粒度的对象。

    比如iOS的RunTime就是享元的一个事件。每个对象调用的方法其实是他对应的类里面实现的。比如NSObject定义了很多方法让所有对象都可以使用。类对象永远只有一个,而对应的实例对象有无数个。

    VC.m

    //享元工厂,里面包括多个共享的对象。
    HCDWebSiteFactory *facoty = [[HCDWebSiteFactory alloc]init];
    //虽然生成了两个fx和fy产品展示类型的对象,但是通过共享只初始化了一个产品展示的对象。
    HCDWebSite fx = [facoty getWebSiteCategory:@"产品展示"];
    HCDUser *user = [[HCDUser alloc]init];
    user.name = @"张三";
    [fx use:user];
    HCDWebSite fy = [facoty getWebSiteCategory:@"产品展示"];
    HCDUser *user1 = [[HCDUser alloc]init];
    user1.name = @"李四";
    [fy use:user1];
    //初始化一个博客类型的对象。以后使用都可以共享使用,因为他们有基本相似的功能。
    HCDWebSite fz = [facoty getWebSiteCategory:@"博客"];
    HCDUser *user2 = [[HCDUser alloc]init];
    user2.name = @"王五";
    [fz use:user2];
    

    HCDWebSiteFactory.h

    @interface HCDWebSiteFactory : NSObject
    @property(nonatomic,strong)NSDictionary *flyweights;
    -(id<HCDWebSite> )getWebSiteCategory:(NSString *)webkey;
    -(NSInteger)getWebSiteCount;
    @end
    

    HCDWebSiteFactory.m

    @implementation HCDWebSiteFactory
    -(instancetype)init{
        self = [super init];
        if (self) {
            _flyweights = [NSDictionary dictionary];
        }
        return self;
    }
    -(HCDWebSite)getWebSiteCategory:(NSString *)webkey{
        __block HCDWebSite webset = nil;
        [self.flyweights enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if (webkey == key) {
                webset = obj;
                *stop = YES;
            }
        }];
        if (webset == nil) {
            HCDConcreteWebSite  *concreteset = [[HCDConcreteWebSite alloc] init];
            concreteset.webName = webkey;
            webset = concreteset;
            NSMutableDictionary *mutabledic = [NSMutableDictionary dictionaryWithDictionary:self.flyweights];
            [mutabledic setObject:webset forKey:webkey];
            self.flyweights = [NSDictionary dictionaryWithDictionary:mutabledic];
        }
        return webset;
    }
    -(NSInteger)getWebSiteCount{
        return self.flyweights.count;
    }
    @end
    

    设计图

    相关文章

      网友评论

          本文标题:结构型之七-享元模式

          本文链接:https://www.haomeiwen.com/subject/jjrvyxtx.html