Last active
April 9, 2019 16:52
-
-
Save shanerk/dbeff4f28e46d97c7f771d4b5a766c3e to your computer and use it in GitHub Desktop.
Delegation Example in Salesforce Apex
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
public class DelegateApex { | |
public interface SObjectDelegate { | |
List<SObject> getObject(String search); | |
} | |
public class AccountDelegate implements SObjectDelegate { | |
public List<SObject> getObject(String searchVar) { | |
List<Account> accounts = [SELECT Id, Name | |
FROM Account | |
WHERE Name LIKE :('%' + searchVar + '%')]; | |
if (accounts != null && accounts.size() > 0) { | |
return (List<SObject>)accounts; | |
} | |
return null; | |
} | |
} | |
public class ContactDelegate implements SObjectDelegate { | |
public List<SObject> getObject(String searchVar) { | |
List<Contact> contacts = [SELECT Id, Name | |
FROM Contact | |
WHERE Name LIKE :('%' + searchVar + '%')]; | |
if (contacts != null && contacts.size() > 0) { | |
return (List<SObject>)contacts; | |
} | |
return null; | |
} | |
} | |
public class DelegateClient { | |
private SObjectDelegate delegate; | |
public DelegateClient(SObjectDelegate delegate) { | |
this.delegate = delegate; | |
} | |
public List<SObject> doSearch(String search) { | |
return delegate.getObject(search); | |
} | |
} | |
public static void delegateExampleRunner() { | |
AccountDelegate ad = new AccountDelegate(); | |
ContactDelegate cd = new ContactDelegate(); | |
DelegateClient dc = new DelegateClient(ad); | |
System.debug(dc.doSearch('a')); // List of Accounts containing 'a' in the name | |
dc = new DelegateClient(cd); | |
System.debug(dc.doSearch('a')); // List of Contacts containing 'a' in the name | |
} | |
} | |
/** | |
Sample Output: | |
09:51:12.24 (118080844)|USER_DEBUG|[49]|DEBUG|(Account:{Id=0016300000dmlgMAAQ, Name=San Antonio Spurs}) | |
09:51:12.24 (42083669)|USER_DEBUG|[51]|DEBUG|(Contact:{Id=0036300000T6MJ3AAN, Name=Manu Ginobilli}, Contact:{Id=0036300000T6MI1AAN, Name=Tim Duncan}) | |
**/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment