《Java与模式》重点总结05.docx
《《Java与模式》重点总结05.docx》由会员分享,可在线阅读,更多相关《《Java与模式》重点总结05.docx(16页珍藏版)》请在冰豆网上搜索。
《Java与模式》重点总结05
第三部分行为模式
十二、不变(Immutable)模式
(1)示例类图
(2)示例代码清单
packagecom.javapatterns.immutable.point;
importjava.io.Serializable;
publicclassPointimplementsSerializable{
privateintx;
privateinty;
publicPoint(intx,inty){
this.x=x;
this.y=y;
}
publicPoint(){
this(0,0);
}
publicPoint(Pointp){
this(p.x,p.y);
}
/**
*ReturnstheXcoordinateofthepointindoubleprecision.
*/
publicdoublegetX(){
returnx;
}
/**
*ReturnstheYcoordinateofthepointindoubleprecision.
*/
publicdoublegetY(){
returny;
}
/**
*Returnsthelocationofthispoint.Thismethodisincludedfor
*completeness,toparallelthegetLocation
methodof
*Component
.
*
*@returnacopyofthispoint,atthesamelocation.
*/
publicPointgetLocation(){
returnnewPoint(x,y);
}
/**
*Setsthelocationofthepointtothespecificedlocation.Thismethodis
*includedforcompleteness,toparallelthesetLocation
*methodofComponent
.
*
*@paramp
*apoint,thenewlocationforthispoint.
*/
publicPointsetLocation(Pointp){
returnnewPoint(p.x,p.y);
}
/**
*Changesthepointtohavethespecificedlocation.
*
*Thismethodisincludedforcompleteness,toparallelthe
*setLocation
methodofComponent
.Itsbehavior
*isidenticalwithmove(int, int)
.
*
*@paramx
*thexcoordinateofthenewlocation.
*@paramy
*theycoordinateofthenewlocation.
*/
publicPointsetLocation(intx,inty){
returnnewPoint(x,y);
}
/**
*Setsthelocationofthispointtothespecifiedfloatcoordinates.
*/
publicPointsetLocation(doublex,doubley){
returnnewPoint((int)Math.round(x),(int)Math.round(y));
}
/**
*Movesthispointtothespecificedlocationinthe
*(x, y)coordinateplane.Thismethodisidenticalwith
*setLocation(int, int)
.
*
*@paramx
*thexcoordinateofthenewlocation.
*@paramy
*theycoordinateofthenewlocation.
*/
publicPointmove(intx,inty){
returnnewPoint(x,y);
}
/**
*Translatesthispoint,atlocation(x, y),by
*dx
alongthexaxisanddy
alongthe
*yaxissothatitnowrepresentsthepoint(x
*+
dx
,y
+
* dy
).
*
*@paramx
*thedistancetomovethispointalongthexaxis.
*@paramy
*thedistancetomovethispointalongtheyaxis.
*/
publicPointtranslate(intx,inty){
returnnewPoint(this.x+x,this.y+y);
}
/**
*DetermineswhetheraninstanceofPoint2D
isequaltothis
*point.TwoinstancesofPoint2D
areequalifthevaluesof
*theirx
andy
memberfields,representingtheir
*positioninthecoordinatespace,arethesame.
*
*@paramobj
*anobjecttobecomparedwiththispoint.
*@returntrue
iftheobjecttobecomparedisaninstanceof
*Point2D
andhasthesamevalues;false
*otherwise.
*/
publicbooleanequals(Objectobj){
if(objinstanceofPoint){
Pointpt=(Point)obj;
return(x==pt.x)&&(y==pt.y);
}
returnsuper.equals(obj);
}
/**
*Returnsastringrepresentationofthispointanditslocationinthe
*(x, y)coordinatespace.Thismethodisintendedtobe
*usedonlyfordebuggingpurposes,andthecontentandformatofthe
*returnedstringmayvarybetweenimplementations.Thereturnedstringmay
*beemptybutmaynotbenull
.
*
*@returnastringrepresentationofthispoint.
*/
publicStringtoString(){
returngetClass().getName()+"[x="+x+",y="+y+"]";
}
}
十三、策略(Strategy)模式
(1)示例类图
(2)示例代码清单
packagecom.javapatterns.strategy.sortarray;
abstractpublicclassSortStrategy{
publicabstractvoidsort();
}
packagecom.javapatterns.strategy.sortarray;
publicclassBinSortextendsSortStrategy{
publicvoidsort(){
//sortinglogichere
}
}
packagecom.javapatterns.strategy.sortarray;
publicclassBubbleSortextendsSortStrategy{
publicvoidsort(){
//sortinglogichere
}
}
packagecom.javapatterns.strategy.sortarray;
publicclassHeapSortextendsSortStrategy{
publicvoidsort(){
//sortinglogichere
}
}
packagecom.javapatterns.strategy.sortarray;
publicclassQuickSortextendsSortStrategy{
publicvoidsort(){
//sortinglogichere
}
}
packagecom.javapatterns.strategy.sortarray;
publicclassRadixSortextendsSortStrategy{
publicvoidsort(){
//sortinglogichere
}
}
packagecom.javapatterns.strategy.sortarray;
publicclassSorter{
/**
*@linkaggregation
*@directed
*/
privateSortStrategysortStrategy;
publicvoidsort(){
sortStrategy.sort();
}
publicvoidsetSortStrategy(SortStrategysort){
this.sortStrategy=sort;
}
}
(3)其它类图
十四、模版方法(TemplateMethod)模式
(1)示例类图
(2)示例代码清单
packagecom.javapatterns.templatemethod.InterestRate;
abstractpublicclassAccount{
protectedStringaccountNumber;
publicAccount(){
accountNumber=null;
}
publicAccount(StringaccountNumber){
this.accountNumber=accountNumber;
}
finalpublicdoublecalculateInterest(){
doubleinterestRate=doCalculateInterestRate();
StringaccountType=doCalculateAccountType();
doubleamount=calculateAmount(accountType,accountNumber);
returnamount*interestRate;
}
abstractprotectedStringdoCalculateAccountType();
abstractprotecteddoubledoCalculateInterestRate();
finalpublicdoublecalculateAmount(StringaccountType,StringaccountNumber){
//retrieveamountfromdatabase...hereisonlyamock-up
return7243.00D;
}
}
packagecom.javapatterns.templatemethod.InterestRate;
publicclassMoneyMarketAccountextendsAccount{
publicStringdoCalculateAccountType(){
return"MoneyMarket";
}
publicdoubledoCalculateInterestRate(){
return0.045D;
}
}
packagecom.javapatterns.templatemethod.InterestRate;
publicclassCDAccountextendsAccount{
publicStringdoCalculateAccountType(){
return"CertificateofDeposite";
}
publicdoubledoCalculateInterestRate(){
return0.065D;
}
}
packagecom.javapatterns.templatemethod.InterestRate;
publicclassClient{
privatestaticAccountacct=null;
publicstaticvoidmain(String[]args){
acct=newMoneyMarketAccount();
System.out.println("InterestearnedfromMoneyMarketaccount="
+acct.calculateInterest());
acct=newCDAccount();
System.out.println("InterestearnedfromCDaccount="
+acct.calculateInterest());
}
}
十五、观察者(Observer)模式
1、方案一
(1)示例类图
(2)示例代码清单
packagecom.javapatterns.observer;
publicinterfaceSubject{
publicvoidattach(Observerobserver);
publicvoiddetach(Observerobserver);
voidnotifyObservers();
}
packagecom.javapatterns.observer;
importjava.util.Vector;
importjava.util.Enumeration;
publicclassConcreteSubjectimplementsSubject{
/**
*@associates<{Observer}>
*@linkaggregation
*@supplierCardinality0..*
*/
privateVectorobserversVector=newVector();
publicvoidattach(Observerobserver){
observersVector.addElement(observer);
}
publicvoiddetach(Observerobserver){
observersVector.removeElement(observer);
}
publicvoidnotifyObservers(){
Enumerationenumeration=observers();
while(enumeration.hasMoreElements()){
((Observer)enumeration.nextElement()).update();
}
}
publicEnumerationobservers(){
return((Vector)observersVector.clone()).elements();
}
}
packagecom.javapatterns.observer;
publicinterfaceObserver{
voidupdate();
}
packagecom.javapatterns.observer;
importjava.util.Observable;
importjava.util.Observer;
publicclassConcreteObserverimplementsObserver{
publicvoidupdate(Observableo,Objectarg){
//Writeyourcodehere
}
}
2、方案二
(1)示例类图
(2)示例代码清单
packagecom.javapatterns.observer.variation;
importjava.util.Vector;
importjava.util.Enumeration;
abstractpublicclassSubject{
/**
*@associates<{Observer}>
*@linkaggregation
*@supplierCardinality0..*
*/
privateVectorobserversVector=newVector();
publicvoidattach(Observerobserver){
observersVector.addElement(observer);
System.out.println("Attachedanobserver.");
}
publicvoiddetach(Observerobserver){
observersVector.removeElement(observer);
}
publicvoidnotifyObservers(){
Enumerationenumeration=observers();
while(enumeration.hasMoreElements()){
System.out.println("Beforenotifying");
((Observer)enumeration.nextElement()).update();
}
}
publicEnumerationobservers(){
return((Vector)observersVector.clone()).elements();
}
}
packagecom.javapatterns.observer.variation;
publicclassConcreteSubjectextendsSubject{
privateStringstate;
publicvoidchange(StringnewState){
state=newState;
this.notifyObservers();
}
}
packagecom.javapatterns.observer.variation;
publicinterfaceObserver{
voidupdate();
}
packagecom.javapatterns.observer.variation;
publicclassConcreteObserverimplementsObserver{
publicvoidupdate(){
System.out.println("Iamnotified");
}
}
packagecom.javapatterns.observer.variation;
publicclassClient{
privatestaticConcreteSubjectsubject;
privatestaticObserverobserver;
publicstaticvoidmain(String[]args){
subject=newConcreteSubject();
observer=newConcreteObserver();
subject