]]>Template模式和Strategey模式http://www.aygfsteel.com/97030530/archive/2006/03/29/38131.html逝去的年?/dc:creator>逝去的年?/author>Wed, 29 Mar 2006 12:49:00 GMThttp://www.aygfsteel.com/97030530/archive/2006/03/29/38131.htmlhttp://www.aygfsteel.com/97030530/comments/38131.htmlhttp://www.aygfsteel.com/97030530/archive/2006/03/29/38131.html#Feedback0http://www.aygfsteel.com/97030530/comments/commentRss/38131.htmlhttp://www.aygfsteel.com/97030530/services/trackbacks/38131.html 在学?fn)Spring的过E中l常看到一些大虾推荐阅读Rod_Johnson?lt;Expert_One-on-One_J2EE_Design_and_Development>?据说此书的第四章每个学java人都要看?好不Ҏ(gu)搞到pdf?可惜是E文的,中文的搞不到,没办法只好硬着头皮看下厅R?br /> W四章主要讲的是面向对象的设计模?怎么采用一致的~码公约,怎么利用也有的系l?q对于理解Spring框架有很大的帮助!因ؓ(f)q是Spring之父的编E思想?: 关于接口的好处及(qing)l合模式的有?我这里就不说了?br /> Template模式:适用范围,我们知道某个业务或算法的步骤,但是不知道怎么把每步的序。Template模式采用在abstractcM有个Public and final的方法封装了调用每步的顺?也就是说控制了工作流E。所有的l承cM只要实现每步的具体Ҏ(gu)。这是控制反转的一U表玎ͼ以前都是我们在程序中去调用API中的Ҏ(gu),现在是我们实现API某个cM的抽象方法给该类调用!q种控制反{的机?是框架的代码基础.比如,EJB中的Init()和destory()Ҏ(gu){等.Spring框架中的Ҏ(gu)据持久层的实现就是很好的例子! 下面把书中的例子COPY? AbstractOrderEJB父类实现了商业逻辑,包括用户是否金额现和对大的订单q行打折,palceOrder()Ҏ(gu)是那个工作方法?/font>
abstractclass AbstractOrderEJB { publicfinal Invoice placeOrder (int customerId, InvoiceItem[] items) throws NoSuchCustomerException, SpendingLimitViolation { int total =0; for (int i =0; i < items. length; i++) { total += getItemPrice (items [i]) * items [i] .getQuantity(); } if (total > getSpendingLimit (customerId) ) { getSessionContext() .setRollbackOnly(); thrownew SpendingLimitViolation (total, limit); } elseif (total > DISCOUNT_THRESHOLD) { // Apply discount to total } int invoiceId = placeOrder (customerId, total, items); returnnew InvoiceImpl (iid, total); } protectedabstractint getItemPrice(InvoiceItem item); protectedabstractint getSpendingLimit(customerId)throws NoSuchCustomerException; protectedabstractint placeOrder(int customerId, int total,InvoiceItem[] items); }
getItemPriceQgetSpendingLimitQplaceOrderq三个方法,是protected and abstract的,由子cL实现?/font> Strategey模式和Template模式比较怼.用Strategey模式对上个例子进行改?把三个单独的Ҏ(gu)攑օ一个接口中,工作方法进行如下修?