ios - The correct realization of the adapter pattern in objective c -
i need create data manager app without hardcoding on 1 file format, if change way of saving data - can easily. purposes choose adapter pattern.
i have datamanager class wrote general methods making data store it.
@protocol datamanagerprotocol @required - (void) readfile; - (void) savefile; @end @interface datamanager : nsobject { nsmutablearray *items; nsmutablestring *destpath; } // many different methods @end
than have datafilemanager there method storing data in 1 specific format:
@interface datafilemanager : nsobject - (void) saveplist; - (void) readplist; @end @implementation datafilemanager - (void) saveplist { nslog(@"the plist file saved."); } -(void) readplist { nslog(@"the plist file readed."); } @end
and have dataadapter convert interfaces:
#import <foundation/foundation.h> #import "datafilemanager.h" #import "datamanager.h" @interface dataadapter : nsobject <datamanagerprotocol> { @private datafilemanager *_datafilemanager; } @property (nonatomic, strong) datafilemanager *datafilemanager; - (id) initwithdatafilemanager:(datafilemanager*) adaptee; @end @implementation dataadapter @synthesize datafilemanager = _datafilemanager; - (id) initwithdatafilemanager:(datafilemanager *) adaptee { self = [super self]; _datafilemanager = adaptee; return self; } - (void) savefile { [_datafilemanager saveplist]; } - (void) readfile { [_datafilemanager readplist]; } @end
so in datamanager file write method:
- (void) savethetestfile:(id)foradapter { [foradapter savefile]; }
and using this:
datafilemanager *datafilemanager = [[datafilemanager alloc] init]; dataadapter *dataadapter = [[dataadapter alloc] initwithdatafilemanager:datafilemanager]; [self savethetestfile:dataadapter];
it works, believe wrong here - there way make more simple? don't use arc , need release lot of filemanagers - it's not good, believe. totally confused in methods. maybe can give more interesting , simple realization of pattern case? thank you!
another solution use category on datamanager class defined inside implementation file of datafilemanager class.
here example how should like:
//class datafilemanager's implementation @implementation datamanager (datafilemanager_adapter) // methods allow datafilemanager connect datamanager // methods datafilemanager can use calculate values dependent on both datamanager // , datafilemanager @end @implementation datafilemanager // datafilemanager's methods @end
the classical approach create third intermediary class have done but, in objective-c, categories eliminate need. adapter interfaces in objective-c, using categories.
Comments
Post a Comment