| |
abstractfactory模式和可扩展性 如果要实现较好的可扩展性,abstractfactory模式确实是一件利器。如上面所说,如果要创建的forum接口的不同实现,而又不想更改代码的话,就需要用到抽象工厂了。再jive中,authorizationfactory类是一个抽象类,用来创建authorization对象。这是一个抽象工厂,可以通过不同的子类来创建不同的authorization对象。这个工厂的实现方法是: 在authorizationfactory中使用一个private static变量factory,用来引用具体的抽象工厂的实例: private static authorizationfactory factory = null; 用一个private static的string,来指明具体的抽象工厂的子类类名: private static string classname ="com.coolservlets.forum.database.dbauthorizationfactory"; 然后是用一个private static的loadauthorizationfactory方法来给这个factory变量赋值,生成具体的抽象工厂类: private static void loadauthorizationfactory() { if (factory == null) { synchronized(classname) { if (factory == null) { string classnameprop = propertymanager.getproperty( "authorizationfactory.classname" ); if (classnameprop != null) { classname = classnameprop; } try { class c = class.forname(classname); factory = (authorizationfactory)c.newinstance(); } catch (exception e) { system.err.println("exception loading class: " + e); e.printstacktrace(); } } } } } 在static的getauthorization方法返回一个authorization的过程中,先初始化工厂类factory变量,然后用factory的createauthorization方法来创建: public static authorization getauthorization(string username, string password) throws unauthorizedexception { loadauthorizationfactory(); return factory.createauthorization(username, password); } 不同的子类有不同的createauthorization方法的实现。比如在dbauthorizationfactory这个authorizationfactory的数据库实现子类中,createauthorization方法是这样实现的: public authorization createauthorization(string username, string password) throws unauthorizedexception { if (username == null || password == null) { throw new unauthorizedexception(); } password = stringutils.hash(password); int userid = 0; connection con = null; preparedstatement pstmt = null; try { con = dbconnectionmanager.getconnection(); pstmt = con.preparestatement(authorize); pstmt.setstring(1, username); pstmt.setstring(2, password); resultset rs = pstmt.executequery(); if (!rs.next()) { throw new unauthorizedexception(); } userid = rs.getint(1); } catch( sqlexception sqle ) { system.err.println("exception in dbauthorizationfactory:" + sqle); sqle.printstacktrace(); throw new unauthorizedexception(); } finally { try { pstmt.close(); } catch (exception e) { e.printstacktrace(); } try { con.close(); } catch (exception e) { e.printstacktrace(); } } return new dbauthorization(userid); } 在这个类中,可以看到抽象类和具体的子类之间的关系,它们是如何协作的,又是如何划分抽象方法和非抽象方法的,这都是值得注意的地方。一般的,抽象方法需要子类来实现,而抽象类中的非抽象方法应该所有子类所能够共享的,或者可是说,是定义在抽象方法之上的较高层的方法。这确实是一个抽象工厂的好例子!虽然实现的方法已经和gof中给出的实现相差较远了,但思想没变,这儿的实现,也确实是要巧妙的些。 还有就是静态方法的使用,使得这个类看起来有些singleton的意味。这使得对于abstractfactory的创建变得简单。 在authorizationfactory中定义的其它方法,涉及到具体的如何创建authorization,都是作为abstract方法出现,具体实现留给子类来完成。 这样,在需要生成一个authorization的时候,只需要调用authorizationfactory的静态方法getauthorization就可以了,由子类实现了具体的细节。 其它的,如同上面讲到的,在创建forum的时候用的forumfactory,具有同上面一样的实现,这就是模式之所以称为模式的所在了。
|
|