《Java与模式》重点总结05.docx

上传人:b****0 文档编号:12711337 上传时间:2023-04-21 格式:DOCX 页数:16 大小:249.10KB
下载 相关 举报
《Java与模式》重点总结05.docx_第1页
第1页 / 共16页
《Java与模式》重点总结05.docx_第2页
第2页 / 共16页
《Java与模式》重点总结05.docx_第3页
第3页 / 共16页
《Java与模式》重点总结05.docx_第4页
第4页 / 共16页
《Java与模式》重点总结05.docx_第5页
第5页 / 共16页
点击查看更多>>
下载资源
资源描述

《Java与模式》重点总结05.docx

《《Java与模式》重点总结05.docx》由会员分享,可在线阅读,更多相关《《Java与模式》重点总结05.docx(16页珍藏版)》请在冰豆网上搜索。

《Java与模式》重点总结05.docx

《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,toparallelthegetLocationmethodof

*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

*setLocationmethodofComponent.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

*(xy)coordinateplane.Thismethodisidenticalwith

*setLocation(int, int).

*

*@paramx

*thexcoordinateofthenewlocation.

*@paramy

*theycoordinateofthenewlocation.

*/

publicPointmove(intx,inty){

returnnewPoint(x,y);

}

/**

*Translatesthispoint,atlocation(xy),by

*dxalongthexaxisanddyalongthe

*yaxissothatitnowrepresentsthepoint(x 

*+ dx,y +

dy).

*

*@paramx

*thedistancetomovethispointalongthexaxis.

*@paramy

*thedistancetomovethispointalongtheyaxis.

*/

publicPointtranslate(intx,inty){

returnnewPoint(this.x+x,this.y+y);

}

/**

*DetermineswhetheraninstanceofPoint2Disequaltothis

*point.TwoinstancesofPoint2Dareequalifthevaluesof

*theirxandymemberfields,representingtheir

*positioninthecoordinatespace,arethesame.

*

*@paramobj

*anobjecttobecomparedwiththispoint.

*@returntrueiftheobjecttobecomparedisaninstanceof

*Point2Dandhasthesamevalues;false

*otherwise.

*/

publicbooleanequals(Objectobj){

if(objinstanceofPoint){

Pointpt=(Point)obj;

return(x==pt.x)&&(y==pt.y);

}

returnsuper.equals(obj);

}

/**

*Returnsastringrepresentationofthispointanditslocationinthe

*(xy)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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 工程科技 > 冶金矿山地质

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1