'Design pattern for adapter class whose functions depend on availability of external SDK
I have an adapter class (ChatSdkAdapter) for external chat Sdk. Chat SDK is not available as an NPM package and is therefore loaded using injection into the document via script tag. Once it is loaded and initialized, it can be accessed from the window object: window.ChatSdk.login()...
ChatSdkAdapter class contains methods such as login, sendMessage..., that all depend on availability of the window.ChatSdk API.
Which method is preferred to solve the coupling between the adapter and the SDK?
Method 1: expose method getInstance in the adapter, that would always return the same instance of the adapter, but before that, check if the window.ChatSdk is available (and if not, return an error). However, what happens if window.ChatSdk is deleted (unloaded), after the instance is created?
Method 2: Add a check if ChatSdk is available in every method of the adapter (EnsureChatSdkAvailable()), as a first line
Which of these is prefered, and is there a better approach?
Thank you in advance.
Solution 1:[1]
Both. Use the safe getInstance() in your class methods to call window.ChatSDK and retrieve it. This way, every method that uses the chat SDK will error our correctly should the SDK not be there anytime.
# pseudocode
Class ChatAdapter {
private chat: ChatSDK
private function initChat(): void {
# what ever you need to do to initialize your chat sdk
# or error if you cant
this.chat = window.ChatSDK
}
private function getChatInstance(): ChatSDK {
if (this.chat ==== undefined) {
this.initChat()
}
return this.chat
}
public function doSomething (): void {
this.getChatInstance().doSomething()
}
}
Essentially, you are doing is the singleton pattern where you have a single instantiation that is held in memory for all instances of your adapter to be calling. Also, you will note that I put an init function because I think its preferred to initialize when you first "need" the chat sdk but if for some reason you can't control the init, then you can error out there.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dan |
