Provider.java
public interface Provider { Service newService(); }
Service.java
public interface Service { // Service-specific methods go here }
Services.java
import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Services { private Services() { throw new AssertionError(); } // Prevents instantiation (Item 4) // Maps service names to services private static final Map<String, Provider> providers = new ConcurrentHashMap<String, Provider>(); public static final String DEFAULT_PROVIDER_NAME = "<def>"; // Provider registration API public static void registerDefaultProvider(Provider p) { registerProvider(DEFAULT_PROVIDER_NAME, p); } public static void registerProvider(String name, Provider p) { providers.put(name, p); } // Service access API public static Service newInstance() { return newInstance(DEFAULT_PROVIDER_NAME); } public static Service newInstance(String name) { Provider p = providers.get(name); if (p == null) throw new IllegalArgumentException( "No provider registered with name: " + name); return p.newService(); } }
Test.java
public class Test { public static void main(String[] args) { // Providers would execute these lines Services.registerDefaultProvider(DEFAULT_PROVIDER); Services.registerProvider("comp", COMP_PROVIDER); Services.registerProvider("armed", ARMED_PROVIDER); // Clients would execute these lines Service s1 = Services.newInstance(); Service s2 = Services.newInstance("comp"); Service s3 = Services.newInstance("armed"); System.out.printf("%s, %s, %s%n", s1, s2, s3); } private static Provider DEFAULT_PROVIDER = new Provider() { public Service newService() { return new Service() { @Override public String toString() { return "Default service"; } }; } }; private static Provider COMP_PROVIDER = new Provider() { public Service newService() { return new Service() { @Override public String toString() { return "Complementary service"; } }; } }; private static Provider ARMED_PROVIDER = new Provider() { public Service newService() { return new Service() { @Override public String toString() { return "Armed service"; } }; } }; }
时间: 2024-10-07 15:13:33