public class Factory{
public static Sample creator(int which){
//getClass 产生Sample 一般可使用动态类装载装入类。
if (which==1) return new SampleA(); else if (which==2) return new SampleB();
}
}
|
public abstract class Factory{
public abstract Sample creator();
public abstract Sample2 creator(String name);
}
public class SimpleFactory extends Factory{
public Sample creator(){
......... return new SampleA }
public Sample2 creator(String name){
......... return new Sample2A }
}
public class BombFactory extends Factory{
public Sample creator(){
...... return new SampleB }
public Sample2 creator(String name){
...... return new Sample2B }
}
|
public abstract class ForumFactory {
private static Object initLock = new Object();
private static String className = "com.jivesoftware.forum.database.DbForumFactory"; private static ForumFactory factory = null;
public static ForumFactory getInstance(Authorization authorization) {
//If no valid authorization passed in, return null. if (authorization == null) { return null; } //以下使用了Singleton 单态模式 if (factory == null) { synchronized(initLock) { if (factory == null) { ......
try {
//动态转载类 Class c = Class.forName(className); factory = (ForumFactory)c.newInstance(); } catch (Exception e) { return null; } } } }
//Now, 返回 proxy.用来限制授权对forum的访问
return new ForumFactoryProxy(authorization, factory, factory.getPermissions(authorization)); }
//真正创建forum的方法由继承forumfactory的子类去完成.
public abstract Forum createForum(String name, String description) throws UnauthorizedException, ForumAlreadyExistsException;
....
}
|
public class CatalogDAOFactory {
/**
* 本方法制定一个特别的子类来实现DAO模式。
* 具体子类定义是在J2EE的部署描述器中。 */
public static CatalogDAO getDAO() throws CatalogDAOSysException {
CatalogDAO catDao = null;
try {
InitialContext ic = new InitialContext();
//动态装入CATALOG_DAO_CLASS //可以定义自己的CATALOG_DAO_CLASS,从而在无需变更太多代码 //的前提下,完成系统的巨大变更。
String className =(String) ic.lookup(JNDINames.CATALOG_DAO_CLASS);
catDao = (CatalogDAO) Class.forName(className).newInstance();
} catch (NamingException ne) {
throw new CatalogDAOSysException("
CatalogDAOFactory.getDAO: NamingException while getting DAO type : /n" + ne.getMessage());
} catch (Exception se) {
throw new CatalogDAOSysException("
CatalogDAOFactory.getDAO: Exception while getting DAO type : /n" + se.getMessage());
}
return catDao;
}
}
|