Seletor和SelectorProvider综合使用了“Simple Factory”和“Factory Method”来应对将来可能的Selector机制和SelectorProvider的变化。使用“Simple Factory”可以提供一种默认工厂,使用起来很方便;使用“Factory Method”能够最大程度的满足实现机制方面的变化。
下面是关于这两个类在工厂模式方面的代码片段
Selector代码:
package java.nio.channels;
import java.io.IOException;
import java.nio.channels.spi.SelectorProvider;
import java.util.Set;
public abstract class Selector {
/**
* Initializes a new instance of this class.
//迫使它的子类必须有一个缺省参数的构造方法
*/
protected Selector() { }
/** 产品本身所提供的服务,相当于Product.service()*/
public abstract int select() throws IOException;
/**
* Opens a selector.
*
* <p> The new selector is created by invoking the {@link
* java.nio.channels.spi.SelectorProvider#openSelector openSelector} method
* of the system-wide default {@link
* java.nio.channels.spi.SelectorProvider} object. </p>
*
* @return A new selector
*
* @throws IOException
* If an I/O error occurs
*/
//静态工厂方法,相当于Product.newDefaultProduct()
public static Selector open() throws IOException {
return SelectorProvider.provider().openSelector();
}
}
SelectorProvider代码:
public abstract class SelectorProvider {
/**
* Initializes a new instance of this class. </p>
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link RuntimePermission}<tt>("selectorProvider")</tt>
*/
//迫使它的子类必须提供一个缺省参数的构造方法
//以支持在反射时,能够确定使用class.newInstance(),不带参的。
protected SelectorProvider() {
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(new RuntimePermission("selectorProvider"));
}
/**
简单工厂方法,通过此方法我们可以获取默认的Provider,关于默认的Provider,
一般会在Sun提出标准的时候,Sun自己也给出一个默认实现。另外,指定标准的团队
也会把设置默认Provider的接口提供出来。
*/
public static SelectorProvider provider() {
synchronized (lock) {
if (provider != null)
return provider; //保证默认Provider是一个单例
return (SelectorProvider)AccessController
.doPrivileged(new PrivilegedAction() {
public Object run() {
if (loadProviderFromProperty())
return provider; //提供一种支持用户自己设置默认Provider的方式
//而且这里的编码风格符合Flower在Refactoring中提倡的
//些原则。
if (loadProviderAsService())
return provider;
provider = sun.nio.ch.DefaultSelectorProvider.create();
//Sun的默认实现
return provider;
}
});
}
}
}
private static final Object lock = new Object();//用来支持默认Provider的单例模式的
private static SelectorProvider provider = null;//用来支持默认Provider的单例模式的
private static boolean loadProviderFromProperty() {
String cn = System.getProperty("java.nio.channels.spi.SelectorProvider");
if (cn == null)
return false;
try {
Class c = Class.forName(cn, true,
ClassLoader.getSystemClassLoader());
provider = (SelectorProvider)c.newInstance();
return true;
} catch (ClassNotFoundException x) {
throw new ServiceConfigurationError(x);
} catch (IllegalAccessException x) {
throw new ServiceConfigurationError(x);
} catch (InstantiationException x) {
throw new ServiceConfigurationError(x);
} catch (SecurityException x) {
throw new ServiceConfigurationError(x);
}
}
}