Last active
August 29, 2015 14:24
-
-
Save miensol/4268ec47392ed4ea232e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package pl.brightinventions.samples; | |
import android.content.Context; | |
import android.content.SharedPreferences; | |
import javax.inject.Singleton; | |
public interface CurrentUserProvider { | |
boolean isLoggedIn(); | |
CurrentUser getCurrentUser(); | |
} | |
class PreferencesSaver { | |
private static final String USER = "user"; | |
private final Context _context; | |
public PreferencesSaver(Context context) { | |
_context = context; | |
} | |
public void savePreferences(CurrentUserProvider userProvider, AppConfig appConfig){ | |
String keyPrefix = "appConfig.defaultUser"; | |
if(userProvider.isLoggedIn()){ | |
keyPrefix = "appConfig." + userProvider.getCurrentUser().getId(); | |
} | |
SharedPreferences preferences = _context.getSharedPreferences(keyPrefix, Context.MODE_PRIVATE); | |
preferences.edit() | |
.putBoolean("useFeatureA", appConfig.useFeatureA) | |
.putBoolean("useFeatureB", appConfig.useFeatureB) | |
.apply(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface UserReference { | |
int getId(); | |
} | |
@Singleton | |
class InMemoryUserSession implements CurrentUserProvider { | |
UserReference _currentUser = new AnonymousUserReference(); | |
@NonNull | |
@Override | |
public UserReference getCurrentUserReference() { | |
return _currentUser; | |
} | |
public void setNewUser(User user){ | |
_currentUser = new RegularUserReference(user); | |
} | |
//NullObject | |
private static class AnonymousUserReference implements UserReference { | |
@Override | |
public int getId() { | |
return -1; | |
} | |
} | |
private static class RegularUserReference implements UserReference { | |
private final User _user; | |
public RegularUserReference(User user) { | |
_user = user; | |
} | |
@Override | |
public int getId() { | |
return _user.getId(); | |
} | |
} | |
} | |
class PreferencesSaver { | |
... | |
public void savePreferences(CurrentUserProvider userProvider, AppConfig appConfig){ | |
String keyPrefix = "appConfig." + userProvider.getCurrentUserReference().getId(); | |
SharedPreferences preferences = _context.getSharedPreferences(keyPrefix, Context.MODE_PRIVATE); | |
... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment