資源描述:
《設(shè)計(jì)模式-6裝飾者模式.ppt》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫(kù)。
1、設(shè)計(jì)模式-裝飾者模式假設(shè)一個(gè)飲料店抽象一個(gè)飲料類但是,就某種飲料來(lái)說(shuō)可以要求在其中加入各種調(diào)料例如:奶,巧克力,糖等加入不同的調(diào)料,會(huì)形成不同名稱的飲料這樣飲料的數(shù)量將會(huì)很多,即繼承于飲料父類的子類將會(huì)很多每個(gè)子類的cost()方法將計(jì)算出特定飲料加上調(diào)料的價(jià)錢這會(huì)造成維護(hù)的噩夢(mèng)如果奶的價(jià)錢上漲如果新增一種調(diào)料現(xiàn)在要以飲料為主體運(yùn)行時(shí)以調(diào)料來(lái)“裝飾”(decorate)飲料定義裝飾者模式publicclassDarkRoastextendsBeverage{publicDarkRoast(){description="DarkRoastCoffee";}publicdoub
2、lecost(){return.99;}}publicclassMochaextendsCondimentDecorator{Beveragebeverage;publicMocha(Beveragebeverage){this.beverage=beverage;}publicStringgetDescription(){returnbeverage.getDescription()+",Mocha";}publicdoublecost(){return.20+beverage.cost();}}publicclassStarbuzzCoffee{publicstatic
3、voidmain(Stringargs[]){Beveragebeverage=newEspresso();System.out.println(beverage.getDescription()+"$"+beverage.cost());Beveragebeverage2=newDarkRoast();beverage2=newMocha(beverage2);beverage2=newMocha(beverage2);beverage2=newWhip(beverage2);System.out.println(beverage2.getDescription()+"$
4、"+beverage2.cost());Beveragebeverage3=newHouseBlend();beverage3=newSoy(beverage3);beverage3=newMocha(beverage3);beverage3=newWhip(beverage3);System.out.println(beverage3.getDescription()+"$"+beverage3.cost());}}實(shí)例假設(shè)你需要打印發(fā)票salesticket,發(fā)票有抬頭、正文和腳注,發(fā)票抬頭可以是企事業(yè)單位,發(fā)票號(hào)等等,腳注也是一樣,可能有很多不同種類的腳注需要打印。如
5、果發(fā)票格式固定那也就沒(méi)必要繼續(xù)討論了,現(xiàn)在的問(wèn)題是,不同的客戶需要的發(fā)票或者收據(jù)的抬頭或腳注,他們需要的條目是不一樣的,有的需要著明單位,有的只需要發(fā)票號(hào),但是腳注需要開(kāi)票人,等等,對(duì)你來(lái)說(shuō)跟現(xiàn)在的Web系統(tǒng)一樣,客戶的要求是動(dòng)態(tài);不過(guò)發(fā)票的正文是不會(huì)變化的,是固定的如果你的發(fā)票格式為:SalesTicketHeader1???????SalesTicketBody???????SalesTicketFooter1那么你可以這樣去創(chuàng)建對(duì)象:newHeader1(newFooter1(newSalesTicket()));如果你的發(fā)票格式為:SalesTicketHead
6、er1???????SalesTicketHeader2???????SalesTicketBody???????SalesTicketFooter1那么你可以這樣去創(chuàng)建對(duì)象:newHeader1(newHeader2(newFooter1(newSalesTicket())));