Service Locator Pattern
Summary: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Sample Code
Code
public interface IServiceLocator
{
T GetService<T>();
}
public class ServiceLocator : IServiceLocator
{
private IDictionary<object, object> services;
public ServiceLocator()
{
services = new Dictionary<object, object>();
this.services.Add(typeof(IStorageService), new CloudService());
this.services.Add(typeof(INetworkService), new WiFiService());
}
public T GetService<T>()
{
try
{
return (T)services[typeof(T)];
}
catch (KeyNotFoundException)
{
throw new ApplicationException("The requested service is not registered");
}
}
}
public interface IStorageService
{
void Store();
}
public class CloudService : IStorageService
{
public void Store()
{
System.Console.WriteLine("Saving file.");
}
}
public interface INetworkService
{
void Connect();
}
public class WiFiService : INetworkService
{
public void Connect()
{
System.Console.WriteLine("Connected to network.");
}
}
Usage
var serviceLocator = new ServiceLocator();
var storage = serviceLocator.GetService<IStorageService>();
var network = serviceLocator.GetService<INetworkService>();
storage.Store();
network.Connect();
Output
Saving file.
Connected to network.
Comments
Post a Comment