Call multiple classes with the same interface

后端 未结 3 617
-上瘾入骨i
-上瘾入骨i 2021-01-06 04:34

I have an interface like

public interface IAddressProvider
{
    string GetAddress(double lat, double long);
}

In my consuming class I wan

3条回答
  •  攒了一身酷
    2021-01-06 05:12

    The fact that you have multiple address-providers is not something the calling code should have to deal with. So create a specific provider-proxy to handle with these multiple providers.

    Like this.

    public interface IAddressProvider {
        string GetAddress(double lat, double long);
    }
    
    public class AddressProviderProxy: IAddressProvider {
        public AddressProviderProxy(IAddressProvider[] providers) {
            _providers = providers; // TODO: Add a NULL guard
        }
    
        private readonly IAddressProvider[] _providers;
    
        string IAddressProvider.GetAddress(double lat, double long) {
            foreach (var provider in _providers) {
                string address = provider.GetAddress(lat, long);
                if (address != null)
                    return address;
            }
            return null;
        }
    }
    
    // Wire up using DI
    container.Register(
        () => new AddressProviderProxy(
            new IAddressProvider[3] {
                cachedAddressProvider,
                localDbAddressProvider,
                externalAddressProvider
            }
        )
    );
    
    // Use it
    IAddressProvider provider = ...from the container, injected..
    string address = provider.GetAddress(lat, long) ?? "no address found";
    

提交回复
热议问题