vendredi 3 juin 2016

Objective-C dynamic implementation

Description + sample + explanation: (You can skip to the question section)

I'd like to make an object instance, which can be implemented by different implementations, depend on a condition (the internet status).

Simple declaration

@interface LoginController : NSObject

/** The currently logged-in User. Nil if not logged-in yet. */
@property (strong, nonatomic) User *currentUser;

// Singleton object
+ (instancetype)shareInstance;

/** Abstract methods, will do nothing if call directly. Use inheritance implements (Online/Offline) instead. */
- (User *)loginByEmail:(NSString *)email password:(NSString *)pwd;

@end

@interface LoginControllerOnline : LoginController
// Login will call request to server.
@end

@interface LoginControllerOffline : LoginController
// Login will check data in coredata.
@end

The LoginController's login method actually do nothing (return nil). Instead, the inherited class (Online/Offline) overwrite the parent login's method, with different implementations (as in comments)

And then, I have a manager to define which class should be in use:

@implement InternetManager

+ (LoginController *)loginController
{
    return [self hasInternet] ? [LoginControllerOnline shareInstance] : [LoginControllerOffline shareInstance];
}

+ (BOOL)hasInternet
{
    // Check with Reachability.
}

@end

This work. But it's not the mechanism I'd like to achieve.

  1. This mean I have 2 instances of inherited LoginController instead of 1.
  2. When internetStatus change from offline to online, I'd like to re-login online (to get session/oauthToken...). But, I'll have to do many things (copy user, change instance, check retained...) before I can actually call from login online

QUESTION:

Is there a way for me to create only one instance of LoginController, which hold the same properties (User), but can has different (dynamic) implementations (Online/Offline)?

Aucun commentaire:

Enregistrer un commentaire