More on IoC Identity and Object Instances.docx
- 文档编号:26195224
- 上传时间:2023-06-17
- 格式:DOCX
- 页数:14
- 大小:21.51KB
More on IoC Identity and Object Instances.docx
《More on IoC Identity and Object Instances.docx》由会员分享,可在线阅读,更多相关《More on IoC Identity and Object Instances.docx(14页珍藏版)》请在冰豆网上搜索。
MoreonIoCIdentityandObjectInstances
MoreonIoCIdentityandObjectInstances
ColinSamplaleanuhadsomegoodcommentsontheIoCentry,andinfacthecaughtmewithmypantsdownontworelatedpoints.Ifyourecall,inthearticleIshowedagreatdealofdistasteforSpring's"prototype"beans,andalsoformethodinjection.Colinresponded:
[...]
-prototypebeans:
I'mpersonallynotabigfanofthetermprototypeasSpringusesit(Iwouldjustcallthemnon-singletons),andIagree100%thatprototypesarerarelyneeded(andthat'swhythedefaultissingleton),butthey_are_neededsometimes.ConsideringthatyouwerecommentingonverboseXMLIamsurprisedyouhaveanissuewiththefactthattheyaredefinedlikeanyotherbean(exceptsetassingleton=false).Whywouldyoumakesomebodycreatetheirownfactorytojustcreateanon-singletoninstance,whenyoucanreusethesameconfigurationmechanismpeoplehavealreeadylearned?
Andyoucouldn'tjustuseagenericfactoryclassthatSpringprovided,sinceyoustillhavetopassinconstructorargsorJavaBeanpropertiessomehow.
-methodinjection:
lookupmethodinjectionisaboutreducingcode,andreducingcoupling.Ifsomebodyisgoingtoinjectafactorywhichistobeusedtoobtainanon-singleton,thentheyhavetocreatethatfactoryclass,andthatclassisalsogoingtobecoupledtoSpringsinceithastoknowhowtogetthenon-singleton.Alternately,theycouldinjectaninstanceofthegenericObjectFactoryfactoryclassweprovideforjustthispurpose,butthentheylosetheadvantageofhavingatypespecificfactory.Anyways,peoplecanuseLookupMethodinjection,theObjectFactoryclass,ortheirownfactoryclasstosolvethisproblem,inthemannertheyfeeliscleanest...
IinitiallyrespondedtoColinsayingthatyoucouldachievemuchthesamethingbyinjectingfactoriesintoservices.Butalas,Iwaswrong.Well,partlywrong.Infact,whileshoweringthismorningIrealizedthatthescenariosthatSpringprototypesandmethodinjectionweremeanttosolveoccuredinseveralcasesinmyownwork!
Ahwell,ina6,000wordarticleIwasboundtogetsomethingswrong....
ToillustratewhyIwaswrongandwhatI'mtalkingabout,letmereferbacktomyownwork.AsImentioned,oneofthecoreservicesinthatcodeissomethingcalledthejobdispatcher,whosepurposeinlifeisreceivejobsfordispatching.Uponreceivingsuchajob,itdispatchesitsomewhere,dependingontheimplementation,typicallyeitherathreadpoolinsidetheprocessortosomeremotecomputingengine.WhatIdidn'tmentionisthatthejobcreatorimplementationsarequitegeneralized,andrelyontheapplicationcodeplugginginclassestoperformtheactualjobs.ThisisbecausejobscontainonlyanID,anoriginatingeventID,ajobtype,andsomeotherbookkeepinginformatin,butinfacttheJobobjectsdon'tcontainanylogictoactuallyrunthejob(e.g.applicationcodedoesn'textendJobwithprocessingcodeoranythinglikethat).Sothejobdispatcher,inparticulartheThreadPoolJobDispatcher,needstomaptheaforementionedjobtypetoaIJobProcessorobjectwhichdoestheactualprocessingwork.
Soweendupinthissituation:
∙ThreadPoolJobDispatcherisanimplementationofIJobDispatcher.It'sasingletonservice.
∙ThreadPoolJobDispatcherhasthisdispatch(Jobjob_)method.Thisis,surprisesurprise,calleddynamicallyanytimesomeonewantstodispatchajobforexecution.
∙Whenthedispatch()methodiscalled,theThreadPoolJobDispatcherneedstodosomethinglikethis:
oSomehowmatchjobtypetoaclassthatcanprocessthatsortofjob.ThisishiddenbehindaIJobProcessorinterface.
oOncethethingisfound,instantiateit.
oPassthejobalongtotheinstantiatedIJobProcessorinterfaceviaitsprocess()method.
∙Here'sthekicker:
theseIJobProcessorobjectstypicallyneedreferencestoservices.
So,ineffect,theIJobDispatcherneedstoinstantiateanIJobProcessorperdispatch()call;andthereareseveralflavorsofIJobProcessor,infactoneperjobtype.Andthesesuckersoftenneedreferencestooneormoresingletonservices;sometimestheIEventManager,whenajobneedstoinjectneweventsintothesystem;sometimestheICacheManagertogetatcacheditems;andsometimesotherthingsis.Itwouldbereally,reallyniceifthesedependenciesweremanagedbytheIoCcontainer.ThisisparticularlytruebecausewhilethecodeseesanIJobProcessorinterface,infacttherearemanyimplementationsofthatinterface,andeachoftheseimplementationsmayhavedifferingdependencies.
Sothisisoursituation:
wehavemanyserviceswhichareofagiventype,sometimesthereareseveralservicesofthesametype.Eachofthesehasawell-definednameorIDwhichcorrespondstoexactlyoneinstance.Wehaveotherobjectswhichneedtobecreatedontheflywhichhavenowell-definedidentity,butwhichdohaveawell-definedtype(IJobProcessor)andofwhichthereareseveralimplementations.
Thereareseveralwaystoapproachthissortofissue.Theobviousnon-IoCwaywouldbetohaveanJobProcessorFactorywhichtakesajobtypeandinstantiatesandreturnsanappropriateobjectforthattype.ButthisfactorynowhastoknowwhatdependencieseachindividualimplementationofIJobProcessorrequires.OK,thisoneneedstheICacheManager;thisoneneedsnothing;thisotheroneneedsICacheManagerandIEventManager;andetcetc.Thisinandofitselfisapain,havingtotrackwhatimplementationhaswhatdependencies.Butitalsomeansthatthefactoryneedstogetthesereferencesitself.Therearetwowaysitcoulddothis:
one,thefactorycouldbeunderIoCcontrolanddeclaredependenciesoneverythingthatanyoftheIJobProcessorsmightrequire.Blech-thiscanoutofhandratherrapidly.Second,thefactorycouldbeawareoftheIoCcontaineranddoaServiceLocator-typelookuptogetthedependenciesasitneedsthem.Blechagain-nowwe'redependentonthecontainer.Andwestillhaveafactorywhichhastobeawareofallthevariousdependencies(ormaybemanyfactories;butstill,that'salotofboilerplatecodewhichisduplicatingdependencyneedsinmultipleplaces).
Anotheralternativewouldbetostillcreateafactory,buthavetheIoCcontainerresolvedependenciesforyou.Thatis,thefactoryinstantiatestheobjectsbutthenpassestheobjectintotheIoCcontainerfordependencyresolution.Sincetheobjectisalreadycreated,thisobviouslyrequiresthatyouusesetterinjection.ThisisinfacttheapproachItakeinmyowncodeatthemoment.ThefactorycreatesIJobProcessesasIneedit,andthenIcallintomyIoCcontainerwithsomethinglikecontainer.resolveDependencies(object).Thecontainerthengoesandresolveswhatsetterdependenciesitcan.ThisisgoodinthatdependencymanagementistakencareofbytheIoCengine.Butitsucksabitbecausethefactoryisinchargeofinstantiation,anditstillhasacontainerdependency.Inthe3IoCcontainersIcompared,IbelievePicoContainersupportsthisasdoesSpring.I'mnotsureifHiveMinddoes.Inanycase,theapproachistocreatetheobjectandthengetthecontainertoresolvedependenciesbypassinginID/typepairs(orjusttypewhenyouhaveonlyoneserviceofagiventype).
YetathirdapproachwouldbeusesomethinglikeSpring'sprototypebeans.Thiswouldremovetheinstantiationresponsibilityfromyourcode.Inmycase,you'dregisterNbeansoftypeIJobProcessor,andeachbean'sIDwouldpointtoanimplementationclass,andforconvenienceprobablyusethejobtypeasthebeanname.NowtheIoCcontainerisdoingalloftheworkforus.Theonlydownsideisthatwestillhavethedrattedcontainerdependency.
ThelastalternativewouldbesomethinglikeSpring'smethodinjection(butmaybenotexactly-commentsfromSpringguyswouldbeappreciatedhere).FromtheSpringexamples,youcandosomethinglikethefollowing.Inmyterminology,aServicewouldimplementanabstractmethod.Thismethodwillactuallybeimplementedbythecontainer,andthecontainerwillmakeitreturnafullyinstantiatedanddependencyresolvedobjectofthetypeyourequire:
Servicecode:
protectedabstractSingleShotHelpercreateSingleShotHelper();
Config:
bean="singleShotHelper"/> ... Sothecontainercreatesa"createSingleShotHelper"methodwhichreturnsaSingleShotHelper;thishelperisinstantiatedanddependencyresolvedlikeanyotherIoCclass. But....inmycase,suchamethodcan'tkeepreturningnewobjectsofthesameimplementation.Ineedittobesmartandreturnbasedonname.WhatwouldbecoolisifSpringsupportedsomethinglikethis(andmaybeitdoes,Icouldn'tquitetellfromthedocs).HereI'musingmyownexample: Servicecode: publicclassThreadPoolJobDispatcher{ [...] publicvoiddispatch(Jobjob_) { [...] IProcessorprocessor=getJobProcessor(job_.getType()); processor.process(job,this); } protectedabstractIJobProcessorgetJobProcessor(Stringid_); } Config: ... Ideally,whatI'dliketoseeisamethodoftheform: protected ...whichSpringcanhookintovialookup-method.Iwouldpresumewhenautowiringwasinfullonmode,Springcanfigureoutwhat
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- More on IoC Identity and Object Instances