Skip to content

Instantly share code, notes, and snippets.

@RasMisha
Created December 14, 2018 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RasMisha/7e3fd416fc0ece062e442ec764e49d03 to your computer and use it in GitHub Desktop.
Save RasMisha/7e3fd416fc0ece062e442ec764e49d03 to your computer and use it in GitHub Desktop.
Salesforce Service Locator
public class CMN_ServiceLocator {
private static final Map<Type, Type> customTypesMap = new Map<Type, Type> {
CMN_IDatabase.class => CMN_Database.class
};
private static Map<Type, Type> testTypesMap = new Map<Type, Type> {
// Mocks
};
private static Map<Type, Object> mocks = new Map<Type, Object> {
// Mocks
};
private static final Map<Type, Object> typeToInstance = new Map<Type, Object>();
public static Type resolve(Type theType) {
if (testTypesMap.containsKey(theType)) {
return testTypesMap.get(theType);
}
if (customTypesMap.containsKey(theType)) {
return customTypesMap.get(theType);
}
return theType;
}
public static Object instance(Type t) {
if (mocks.containsKey(t)) {
return mocks.get(t);
}
Type resolved = resolve(t);
if (!typeToInstance.containsKey(resolved)) {
typeToInstance.put(resolved, resolved.newInstance());
}
return typeToInstance.get(resolved);
}
@TestVisible
private static void setMock(Type originalType, Type mockType) {
testTypesMap.put(originalType, mockType);
}
@TestVisible
private static void setMock(Type originalType, Object mock) {
mocks.put(originalType, mock);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment