I need to implement a upload file service, so i have a classe named UploadService
with one method named Upload
. I have 3 integrations 3rd party to use: AwsS3
, Google Storage
and Azure Storage
, but my class service dont need to know which intergration it will use and even know how to integrate with them. I was looking to the following patterns: Abstract Factory
, to choose and create my upload integration class in runtime and the pattern Adapter
to create a solid contract between my UploadService
class domain and 3rd party integrations classes. So my code looked like this:
UploadService
class:
public class UploadService
{
private IUploadAdapter _adapter;
public UploadService(IUploadFactory factory)
{
_adapter = factory.Create();
}
public void Upload(File file)
{
_adapter.Upload(file);
}
}
UploadFactory
class which switch a enum UploadApi that come from environments variables:
public class UploadFactory : IUploadFactory
{
private IAwsS3Adapter _awsS3Adapter;
private IGoogleStorageAdapter _googleStorageAdapter;
private IAzureStorageAdapter _azureStorageAdapter;
public UploadFactory(IAwsS3Adapter awsS3Adapter, IGoogleStorageAdapter googleStorageAdapter, IAzureStorageAdapter azureStorageAdapter)
{
_awsS3Adapter = awsS3Adapter;
_googleStorageAdapter = googleStorageAdapter;
_azureStorageAdapter = azureStorageAdapter;
}
public IUploadAdapter Create()
{
switch(UploadApi)
{
case "AwsS3": return _awsS3Adapter;
case "GoogleStorage": return _googleStorageAdapter;
case "AzureStorage": return _azureStorageAdapter;
}
}
}
Each interface IAwsS3Adapter
, IGoogleStorageAdapter
and IAzureStorageAdapter
implements IUploadAdapter
.