samedi 28 février 2015

Is it design pattern: create object with identifier or return if already exists?

main principles:




  • object could be created through class method by providing unique identifier (whatever)




  • if object with given identifier doesn't exists, returned new object otherwise returned existing one




So main point in keeping objects with unique filed (f.e id) for future using, since they might have own states (f.e loading, loaded so on) we are allowed to use it everywhere we need it without re-creating.


Is it design pattern?


F.e:


Advirtisement.h



@interface Advertisment : NSObject

+ (instancetype)adWithID:(NSString *)adID;
+ (NSMutableArray *)sharedAds;


Advertisement.m



+ (instancetype)adWithID:(NSString *)adID {

NSMutableArray *ads = [[self class] sharedAds];
// Look for existing ad based on the id
Advertisement *returnableAd = nil;
for (Advertisement *currentAd in ads) {
if ([currentAd.adID isEqualToString:adID]) {
returnableAd = currentAd;
break;
}
}
// Create a new ad instance for this id if one doesn't already exist.
if (!returnableAd) {
returnableAd = [[[self class] alloc] initWithID:adID];
[ads addObject:returnableAd];
}
return returnableAd;
}
}

+ (NSMutableArray *)sharedAds
{
static NSMutableArray *sharedAds;

@synchronized(self) {
if (!sharedAds) {
sharedAds = [NSMutableArray array];
}
}
return sharedAds;
}

Aucun commentaire:

Enregistrer un commentaire