生活随笔
收集整理的這篇文章主要介紹了
《研磨设计模式》chap22 装饰模式Decorator(4)AOP+总结
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. AOP面向方面編程
共性功能
AOP調(diào)用示意圖
public class SaleModel { private String goods
; //銷售的商品 public String getGoods() {return goods
;}public void setGoods(String goods) {this.goods = goods
;} public String toString(){return
"商品名稱="+goods+
",購(gòu)買數(shù)量="+saleNum
;}
}public interface GoodsSaleEbi {//保存銷售信息,本來(lái)銷售數(shù)據(jù)應(yīng)該是多條,太麻煩了,為了演示,簡(jiǎn)單點(diǎn) public boolean
sale(String user,String customer,SaleModel saleModel
);
}public class GoodsSaleEbo implements GoodsSaleEbi{ public boolean sale(String user,String customer, SaleModel saleModel) {System.out.
println(user+
"保存了"+customer+
"購(gòu)買 "+saleModel+
" 的銷售數(shù)據(jù)");return true
;}
}public abstract class Decorator implements GoodsSaleEbi{ protected GoodsSaleEbi ebi
; //持有被裝飾的組件對(duì)象 public Decorator(GoodsSaleEbi ebi){this.ebi = ebi
;}
}//實(shí)現(xiàn)權(quán)限控制
public class CheckDecorator extends Decorator{public CheckDecorator(GoodsSaleEbi ebi){super(ebi
);} public boolean sale(String user,String customer, SaleModel saleModel) {//簡(jiǎn)單點(diǎn),只讓張三執(zhí)行這個(gè)功能if(!"張三".equals(user)){System.out.
println("對(duì)不起"+user+
",你沒(méi)有保存銷售單的權(quán)限");//就不再調(diào)用被裝飾對(duì)象的功能了return false
;}else{return this.ebi.
sale(user, customer, saleModel
);} }
}public class LogDecorator extends Decorator{public LogDecorator(GoodsSaleEbi ebi){super(ebi
);}public boolean sale(String user,String customer, SaleModel saleModel) {//執(zhí)行業(yè)務(wù)功能boolean f = this.ebi.
sale(user, customer, saleModel
);//在執(zhí)行業(yè)務(wù)功能過(guò)后,記錄日志DateFormat df = new
SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");System.out.
println("日志記錄:"+user+
"于"+df.
format(new
Date())+
"時(shí)保存了一條銷售記錄,客戶是"+customer+
",購(gòu)買記錄是"+saleModel
);return f
;}
}public class Client {public static void main(String[] args) {//得到業(yè)務(wù)接口,組合裝飾器GoodsSaleEbi ebi = new
CheckDecorator(new
LogDecorator(new
GoodsSaleEbo()));//準(zhǔn)備測(cè)試數(shù)據(jù)SaleModel saleModel = new
SaleModel();saleModel.
setGoods("Moto手機(jī)");saleModel.
setSaleNum(2
);//調(diào)用業(yè)務(wù)功能ebi.
sale("張三",
"張三豐", saleModel
);ebi.
sale("李四",
"張三豐", saleModel
);}
}
2. 總結(jié)
2.1 優(yōu)點(diǎn)
- 比繼承更靈活
.從為對(duì)象添加功能的角度來(lái)看,裝飾模式比繼承更靈活。繼承是靜態(tài)的,而且一旦繼承所有子類都有一樣的功能。而裝飾模式采用把功能分離到每個(gè)裝飾器當(dāng)中,然后通過(guò)對(duì)象組合的方式,在運(yùn)行時(shí)動(dòng)態(tài)地組合功能,每個(gè)被裝飾的對(duì)象最終有哪些功能,是由運(yùn)行期動(dòng)態(tài)組合的功能來(lái)決定的。 - 更容易復(fù)用功能
裝飾模式把一系列復(fù)雜的功能分散到每個(gè)裝飾器當(dāng)中,一般一個(gè)裝飾器只實(shí)現(xiàn)一個(gè)功能,使實(shí)現(xiàn)裝飾器變得簡(jiǎn)單,更重要的是這樣有利于裝飾器功能的復(fù)用,可以給一個(gè)對(duì)象增加多個(gè)同樣的裝飾器,也可以把一個(gè)裝飾器用來(lái)裝飾不同的對(duì)象,從而實(shí)現(xiàn)復(fù)用裝飾器的功能。
簡(jiǎn)化高層定義
2.2 缺點(diǎn)
會(huì)產(chǎn)生很多細(xì)粒度對(duì)象。
2.3 裝飾模式的本質(zhì):動(dòng)態(tài)組合
總結(jié)
以上是生活随笔為你收集整理的《研磨设计模式》chap22 装饰模式Decorator(4)AOP+总结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。