资源描述:
《Effective_Java_2 Reloaded》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、EffectiveJava™ReloadedJoshuaBlochChiefJavaArchitectGoogleInc.Session15122006JavaOneSMConference
2、SessionTS-1512
3、DisclaimerEffectiveJava™Hasn’tYetBeenReloaded,butIHavePlentyofAmmunitionIhavelotsoffinenewmaterialonmakingeffectiveuseofnewplatformfeatures,andI’dliketosharesomeofitwithyou
4、2006JavaOneSMConference
5、SessionTS-1512
6、2MenuAppetizer:ObjectCreationMainCourse:GenericsDessert:AssortedSweets2006JavaOneSMConference
7、SessionTS-1512
8、3MenuAppetizer:ObjectCreationMainCourse:GenericsDessert:AssortedSweets2006JavaOneSMConference
9、SessionTS-1512
10、41.StaticFactoriesHaveAdva
11、ntagesOverConstructors(OldNews)•Neednotcreateanewobjectoneachcall•Theyhavenames•Allowsmultiplefactorieswithsametypesignature•Flexibilitytoreturnobjectofanysubtype•Butwait!There’smore…2006JavaOneSMConference
12、SessionTS-1512
13、5NewStaticFactoryAdvantage:TheyDoTypeInference•WhichLooksBett
14、er?•Map>m=newHashMap>();•Map>m=HashMap.newInstance();•RegrettablyHashMaphasnosuchmethod(yet)•Untilitdoes,youcanwriteyourownutilityclass•Yourgenericclassescanandshould2006JavaOneSMConference
15、SessionTS-1512
16、62.StaticFactories
17、andConstructorsShareaProblem•Uglywhentheyhavemanyoptionalparameters•newNutritionFacts(Stringname,intservingSize,intservingsPerCntnr,inttotalFat,intsaturatedFat,inttransFat,intcholesterol,15moreoptionalparams!);•Telescopingsignaturepatternisahackn•Butyoucan’tprovideall2possibilities•
18、Beans-stylesettersarenottheanswer!•Theyprecludeimmutableclasses2006JavaOneSMConference
19、SessionTS-1512
20、7TheSolution:BuilderPattern•Builderconstructortakesallrequiredparams•Onesetterforeachoptionalparameter•Settersreturnthebuildertoallowforchaining•Onemethodtogenerateinstance•Patterne
21、mulatesnamedoptionalparameters!NutritionFactstwoLiterDietCoke=newNutritionFacts.Builder("DietCoke",240,8).sodium(1).build();2006JavaOneSMConference
22、SessionTS-1512
23、8BuilderExamplepublicclassNutritionFacts{publicclassBuilder{publicBuilder(Stringname,intservingSize,intservingsPerContai
24、ner){...}publicBuil