Tải bản đầy đủ - 0 (trang)
Chapter 16. Patterns and Strategies in EJB Design

Chapter 16. Patterns and Strategies in EJB Design

Tải bản đầy đủ - 0trang

WhatArePatterns?

Apatterndescribesaprovenapproachforsolvingaproblem.

Throughouttherestoftheengineeringcommunity,theconcept

ofpatternsisusedextensively.Whencivilengineersare

designinganewbridge,theydon'tstartoutbyproposingtheir

owntheoriesonhowtobestbuildabridge.Theyinsteadtake

advantageoftheknowledgeaccumulatedbythethousandsof

engineerswhohavebuiltproperlyfunctioningbridgesbefore

them.Insomecases,thisknowledgehascomethehardwayas

ideasthatlookedgoodonpapergotaddedtothelistofthings

nottodo.Nomatterhowthebestpatternsfordesigninga

bridgehavebeendeveloped,theydefinethestartingpoint

whenanewbridgeneedstobebuilt.

Askilledcivilengineerknowstostartwithwhat'sbeenlearned

fromtheexperienceofothers.Withtheexceptionofcosmetic

issues,there'srarelyaneedtogooutsidetheexisting

knowledgebaseofsuccessfulbridgedesigns.That'snottosay

thatthereisn'tstillworktobedone.Everybridgeisuniqueand

mustsatisfyitsexactsetofrequirements.Thetrickistoknow

howtoselectthepatternsthatapplytoaparticulardesignand

usethemcorrectly.

Theconceptofsoftwarepatternsisnotmuchdifferentthan

applyingpatternsinotherdisciplines.Softwaredevelopershave

beenbuildingsystemsformanyyears.Someofthedesigns

thatwerechosenworkedverywellandsomedidnot.Theidea

ofsoftwarepatternsistounderstandwhichonesworkedandto

applythesamesolutionwhenfacedwiththesameproblemor

onesimilartoit.Oftenit'sequallyusefultoknowabout

attemptedsolutionsthatfailedandtounderstandwhythey

failedwhenanewpatternisproposed.Softwarepatternscan

bethoughtofasreusableideasorsolutionstosolveagiven

problem.Tomakethemeasiertoreuse,patternsareusually

definedsothatthey'refocusedonasingledesignissue.



Anotheradvantageofunderstandingandusingpatternsisthat

itallowsthosewhounderstandthepatterntocommunicatea

greatdealofinformationveryquickly.Ifyouattendadesign

reviewandsomeonesays"Iusedtheblahpatternhere"and

youunderstandwhatthe"blah"patternisandwhatproblemit

solves,youcangainaquickunderstandingofthatpartofthe

design.Insteadofhavingtostudyeverydetailofthedesign,

youcanfocusonlyonmakingsurethattheselectedpatternis

applicabletotheproblemathand.Patternsallowdevelopersto

exchangeagreatdealofinformationsimplybycommunicating

apatternname.

Differenttypesofpatternsareusedthroughoutthesoftware

community.Patternsareoftengroupedasanalysispatterns,

designpatterns,constructionpatterns,andsoon.Thereare

alsomanyclassificationsofpatternswithinthesegroups.For

example,somepatternsareclassifiedasproxypatternsand

othersareknownasbuilderpatterns.Classifyingpatternshelps

youknowwhichpatternstoconsiderbasedonwhataspectofa

designyou'readdressingatthetime.Theideaistohavea

catalogofpatternsyoucanturntoandpulloutwhatyouneed.

Thestandardforsoftwaredesignpatternswassetbythebook

DesignPatterns:ElementsofReusableObject-Oriented

SoftwarebyErichGamma,RichardHelm,RalphJohnson,and

JohnVlissides.You'lloftenheartheseauthorsandtheirbook

referredtoastheGangofFour(GoF).Ifyou'veeverheardof

patternssuchasSingletonorComposite,thisisthebookthat

definesthem.It'sahighlyregardedbookthatshouldbepartof

everydeveloper'slibrary.Thedocumentationitprovidesfor

eachpatternincludesanameforthepattern,adescriptionof

theproblemit'stryingtosolve,andadescriptionandexample

ofthesolution.Differentdevelopersandorganizationstendto

followtheirownformatsfordocumentingsoftwarepatterns,but

you'llusuallyseethesamebasicinformationcovered.



StrategiesforEnterpriseJavaBeans

Thehistoryofsoftwaredevelopmentisquiteshortwhen

comparedtootherengineeringdisciplines.Thisiswhysoftware

isoftenseenasanimmatureprofessionrelativetoother

technicalfields.Accumulatingprovenpatternsthatareshared

bythedevelopercommunityisawaytofurtheritsprogress

towardmaturity.Someresultsofthisprogressareseeneach

timethebarisraisedonwhatpartsofaprogramanapplication

developerisresponsiblefordesigningandcoding.Justas

standardcommunicationsfunctionalitybuiltontopofTCP/IP

freeddevelopersfromnetworkingdetails,EJBusesmany

provenideasfortransactionalprocessinganddistributed

applicationdevelopmenttomovedeveloperstoanevenhigher

level.

WhenyoubuildanEJBapplication,youaretakingadvantageof

thepastexperienceofEJB'sdesignerswithouthavingto

readdressproblemsthathavebeenhandledforyou.Everything

thathappensunderthehoodusestestedsolutionssothatyou

don'thavetoreinventthewheeleachtimeyoubuildan

application.

Justassoftwareisayoungdisciplinecomparedtomanyothers,

EJBisyoungcomparedtoothersoftwareapproaches.It'sof

courseanevolutionofwhat'sbeendonealreadywith

transactionalanddistributedsystems,butthere'sstill

knowledgetobegainedabouthowtobestbuildapplicationson

topofEJB.Thegoalofthischapteristointroduceyoutosome

oftheknowledgethat'sbeenaccumulatedsofarbytheEJB

developmentcommunity.Someoftheideaspresentedherecan

bedescribedaspatterns,andsomeothersaremorelike

strategiestoconsiderwhendesigningpartofanEJB

application.Thisisn'tapatternsbook,soaformalapproachfor

presentingthismaterialisavoidedhere.Theintentismoreto

conveytheimportanceofunderstandingdesignpatternsand



theseproposedstrategiesforbuildingEJBapplications.Bothare

veryimportantinbuildingresilientsoftwaresystems.

Beforegettingtothedetails,wewanttomakeitclearthat

we'renotthefirsttounderstandtheimportanceofthese

strategies.Wearemerelydocumentingapproachesthatare

takingshapewithinEJBdevelopmentthatwehavefoundtobe

usefulwhilebuildingourownEJBapplications.Theideas

presentedinthischaptercomefromsuchsourcesasWebsites,

mailinglists,newsgroups,articles,otherbooks,andofcourse,

ourownexperiences.JustasmanyoftheGoFpatternshave

becomeingrainedinthesoftwaredevelopmentindustry,several

oftheconceptssummarizedhereareapproachingsimilarstatus

amongEJBdevelopers.Manyofthedesignapproaches

presentedherehaveevolvedfromtheworkofseveralsources,

soit'sdifficulttogivecredittoindividualsfortheseideasjustas

it'sdifficulttocreditsourcesfortheideasthatwentintotheEJB

specification.Ourgoalistoassistinpromotingthese

approachesandsharingthemwithasmanydesignersand

developersaspossibletohelpraisethebarofourcraftonce

again.



DesigningEJBClassesandInterfaces

Thefollowingstrategiesapplytodesigningyourenterprisebean

implementationclassesandtheinterfacestheyexposetotheir

clients.ThecoreofanEJBapplicationconsistsoftheenterprise

beansit'sbuilton,sothisisthefirstplacetofocusyourefforts

towardproducingagooddesign.



DesigningCoarse-GrainedEnterpriseBeans

PriortoEJB2.0,itwasclearthatanenterprisebeanwastoo

heavyanimplementationapproachforsomeobjects.As

Chapter3pointedout,theoverheadinvolvedinmakinga

remotemethodcallcanbequiteexpensive.Theseandother

issuesforcedmanyEJBapplicationstolimitthenumberofcalls

aclientinvokedonanEJBanditalsobecamemoreefficientto

packageuplargeramountsofdatawhencommunicatingtoand

fromenterprisebeans.Thetermthatwasoftenusedforthis

approachwascoarse-grained.However,withthereleaseofthe

EJB2.0Specificationandtheintroductionoflocalinterfaces,

younowhaveachoicetomakeregardingwhetheryouutilize

coarse-grainedorfine-grainedaccessforyourenterprisebeans.

Thedecisioniswhetheryourenterprisebeansneedtobe

exposedtoremoteclientsorwhetherlocalinterfaceswill

suffice.Chapter3providedafewguidelineswhenattemptingto

decidebetweenlocalandremoteexposure.Agoodruleof

thumbistouseremoteinterfacesforyoursessionbeansand

localinterfacesforentitybeans.Thisrulewillnotworkinall

situations,butitisagoodstartingpoint.



UsingaBusinessMethodInterface

Anenterprisebeanclassmustimplementthebusinessmethods

declaredinitscomponentinterface.That'sastraightforward



requirementfundamentaltoEJB,butthere'snodefault

mechanisminplacetoenforcethisuntilabeanisdeployed.A

mismatchbetweenabeanclassanditscomponentinterfaceis

notthekindofproblemadeployershouldhavetoface.Thisis

anerrorthatneedstobedetectedwhenabeaniscompiled.As

youknow,thebuilt-inwaytoforceaclasstoimplementa

particularmethodinJavaistodeclaretheclasstoimplement

aninterfacethatincludesthemethod.Giventhat,itmakes

sensethataninterfaceneedstocomeintoplayhere.Yourfirst

thoughtmightbetodeclarethebeantoimplementits

componentinterfacegiventhatitsbusinessmethodsare

alreadydeclaredthere.Thereareactuallytworeasonswhythis

isn'tarecommendedapproach.

Thefirstreasonwhyabeanshouldn'timplementitscomponent

interfaceisthateverycomponentinterfaceeitherextends

javax.ejb.EJBLocalObjectorjavax.ejb.EJBObject,

dependingonwhetherthebeanisexposedtoalocalorremote

clientrespectively.Ifthebeanisexposedtoaremoteclient,

thenitscomponentinterfacemustextend

javax.ejb.EJBObject,whichinturnextends

java.rmi.Remote.Theseinterfacessupportremoteaccessby

aclientandexposesomeofthehelperfunctionalitythe

containerimplementsforyou.Ifabeanclassimplemented

EJBObject,itwouldhavetoimplementmethodssuchas

getEJBHomeandgetHandle.Besidesplacingextraworkon

theprogrammer,thechiefdrawbackwiththisoptionisthat

thesemethodimplementationswouldneverbecalled.Thisis

becausethecontainer'simplementationoftheremoteinterface

interceptsallcallsfromclients,anditalwaysinvokesthe

container'simplementationoftheEJBObjectmethodswhen

they'recalled.Youcouldprovidedo-nothingimplementations

forthemtosaveyourselfsomework,butthatwouldjustclutter

yourclassdeclarationswithuselessmethods.

Ifyourbeansupportslocalclientaccess,itscomponent

interfacemustextendjavax.ejb.EJBLocalObject.Even



thoughthiscomponentinterfacedoesn'textend

java.rmi.Remote,therearestillmethodsinthisinterface

thatthecontainerisdesignedtoimplement.Regardlessofthe

componentinterfacetype,ifyourenterprisebeanclass

implementedtheinterface,itwouldhavetoprovide

unnecessarymethodimplementationsthatwouldneverbe

invoked.

Thesecondreasonhastodowiththefactthataclientshould

neveraccessanenterprisebeandirectly.Aclientshouldalways

useacomponentinterfacereferencetoaccessanEJB.A

componentinterfacereferenceisassociatedwithaclassthatis

createdbythecontaineratdeploymenttimetoimplementthe

bean'scomponentinterface.Thisisthemeansofaccess

intendedforaclientregardlessofwhethertheclientislocalor

remoteorwhethertheclientisinthesameoradifferent

container.It'sthisseparationbetweenthereferenceheldbya

clientandabeaninstancethatallowsthecontainertopassivate

entityandstatefulsessionbeanobjectsandtoreusestateless

sessionbeansformultipleclients.Methodsthatreturna

referencetoanEJBoracceptoneasamethodparameter

shouldalwaysbedeclaredusingthebean'scomponentinterface

typeandnottheimplementationclass.Thispracticeprevents

aninstanceofanenterprisebeanfrompassingareferenceto

itselfasanargumenttoamethodorreturningathis

referencefromamethod.Whenabeanmethodneedstosupply

areferencetoitsassociatedcomponentinterface,youcanget

thereferenceyouneedbycalling



context.getEJBObject()

or



context.getEJBLocalObject()

wherecontextiseitheranEntityContextora

SessionContextobjectthathasbeenassociatedwiththe



enterprisebean.

Thisseparationcanbreakdownifabeanclassisdeclaredto

implementitscomponentinterface.Withthattypeof

declaration,thecompilerwouldconsiderpassingthisjustas

acceptableaspassingcontext.getEJBObject()wherevera

remoteinterfacereferenceisneeded.Bynotimplementingthe

componentinterface,thecompilercanverifythatanenterprise

beaninstanceisneverpassedasanargumentorreturnedfrom

amethodcalldirectly.

Giventhatdeclaringanenterprisebeantoimplementits

componentinterfaceisn'tagoodapproach,youneedadifferent

waytoensurethatabeanimplementsallthebusinessmethods

declaredinitscomponentinterface.Justtobeclear,business

methodsarethefunctionalmethodsdeclaredbyabean(they

don'tincludethecontainercallbackmethodsortheremote

methodsneededbecauseofthedistributednatureofthe

architecture).Usinganinterfaceisstilltherightapproachhere,

butthecomponentinterfaceisn'ttherightonetouse.What's

insteadrecommendedistodeclareanewinterfacethat

includesonlythebusinessmethodsexposedbyanEJB.This

interfacecanthenbeextendedbythebean'scomponent

interfaceandimplementedbythebeanclass.Thisallowsthe

compilertoverifythatthebeanclassimplementsallthe

requiredmethodsbutitdoesn'timposeanyunnecessary

requirementsonthebeanclass.Thisapproachisknownasthe

BusinessInterfacepattern.Listing16.1showsabasicbusiness

interfaceforalocalclient.

Listing16.1IEnglishAuction.java–ALocalBusiness

InterfacefortheEnglishAuctionEntityBean



/**

packagecom.que.ejb20.auction.model;

*Title:IEnglishAuction





*Description:Localbusinessmethodinterfaceforth

*entitybean



*/

importjava.sql.Timestamp;

importcom.que.ejb20.auction.exceptions.InvalidAuctionS

importcom.que.ejb20.auction.exceptions.InvalidBidExcep

importcom.que.ejb20.auction.view.AuctionDetailView;

importcom.que.ejb20.auction.view.BidView;

importcom.que.ejb20.item.model.Item;

publicinterfaceIEnglishAuction{

publicIntegergetId();

publicvoidsetName(StringnewName);

publicStringgetName();

publicvoidsetDescription(StringnewDescription);

publicStringgetDescription();



publicvoidsetStatus(StringnewStatus)throwsInvali

publicStringgetStatus();

publicvoidsetStartingBid(DoublenewStartingBid)

throwsInvalidAuctionStatusException;

publicDoublegetStartingBid();



publicvoidsetMinBidIncrement(DoublenewMinBidIncrem

throwsInvalidAuctionStatusException;

publicDoublegetMinBidIncrement();



publicvoidsetReserveAmount(DoublenewReserveAmount)

throwsInvalidAuctionStatusException;

publicDoublegetReserveAmount();



publicvoidsetStartDateTime(TimestampnewStartDateTi

throwsInvalidAuctionStatusException;

publicTimestampgetStartDateTime();



publicvoidsetScheduledEndDateTime(TimestampnewSche

throwsInvalidAuctionStatusException;

publicTimestampgetScheduledEndDateTime();



publicvoidsetActualEndDateTime(TimestampnewActualE

publicTimestampgetActualEndDateTime();



publicvoidassignItem(ItemnewItem,intnewQuantity)

throwsInvalidAuctionStatusException;

publicItemgetItem();

publicIntegergetQuantity();

publicvoidremoveItem()throwsInvalidAuctionStatusE



/**

*Submitabidtoanopenauction

*

*@parambidAmounttheamountofthebid

*@parambiddertheparticipantsubmittingthebid

*@returntheautomaticallyassignedbidtransaction

*@throwsInvalidBidExceptionifthebiddoesnotme

*thenextacceptablebid

*@throwsInvalidAuctionStatusExceptioniftheaucti

*/

publicStringsubmitBid(doublebidAmount,Bidderbidd

throwsInvalidBidException,InvalidAuctionStatusExc

/**

*Determinethenextrequiredbidforanauction



*

*@returnthenextacceptablebidamount

*/

publicdoublecomputeNextBidAmount()

throwsInvalidAuctionStatusException;

publicBidViewgetLeadingBidView();

publicBidViewgetWinningBidView();

publicAuctionDetailViewgetAuctionDetail();

/**

*Getthetimeremainingbeforetheauctioncloses

*

*@returnthetimeremaininginmsec

*/

publiclonggetTimeLeft();



/**

*Reportwhetherornotthecurrentleadingbidsati

*

*@returntrueifthereservehasbeenmetorthere

*atleastonebidhasbeensubmitted

*/

publicbooleanreserveMet();



/**

*Assignthecurrentleadingbidastheauctionwinn

*

*@throwsInvalidAuctionStatusExceptioniftheaucti

*/

publicvoidassignWinner()throwsInvalidAuctionStatu



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 16. Patterns and Strategies in EJB Design

Tải bản đầy đủ ngay(0 tr)

×