静态工厂方法+服务提供者框架模板

Posted 力奋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了静态工厂方法+服务提供者框架模板相关的知识,希望对你有一定的参考价值。

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";
				}
			};
		}
	};
}

 

以上是关于静态工厂方法+服务提供者框架模板的主要内容,如果未能解决你的问题,请参考以下文章

服务提供者框架

《Effective Java》服务提供者框架

(EffectiveJava3rd条目一).静态工厂的第5个优点是,在编写包含该方法的类时,返回的对象的类不需要存在。

Effective java 第二章创建和销毁对象 读书笔记

0006JDK源码分析之服务提供者框架

设计模式