Professional Documents
Culture Documents
Whichpropertiesmakeasoftwaresystemhighquality?
correctness,efficiency,easeofuse,reliability/robustness,maintainability,modifiability,
extensibilityandscalability.
MemorizetheSoftwareDevelopmentLifecyclechart
Otherstepstoconsider:SoftwareIntegration,SoftwareMaintenance
SoftwareMaintenance:followsdeployment,monitoringandupdatingdeployedsoftware
UpdatedSoftwareDevelopmentLifecycle:
1) RequirementAnalysis
2) Design
3) EvalueDesign
4) Code
5) Test,Debug,&ProfileComponents
6) Integrate
7) Test,Debug,&ProfileWholeProgram
8) Deploy
9) Maintain
*Notethattherearemanyvariationtothesesteps*
Whatisaframework?
Frameworkismanyclassesworkingtogetherthatcooperatetogethertobuildnew
applicationsandotherframeworks.Frameworkdevelopersmustexplainhowtousethem
throughAPI,commentingandtutorials.
Revision Control
__________________________________________________________________________
Revisioncontrol(alsoknownasversioncontrol,sourcecontrol,andsourcecode
management)isthemanagementofchangestodocuments,computerprograms,largeweb
sites,andothercollectionsofinformation.Helpskeepahistoryofchangesforindividualsand
teamstoshareanddistributecommonsourcecode.
VersionControlsystemServices
BackupandRestore,Synchronization,shorttermundo,Longtermundo,TrackChanges,
TrackOwnership,Sandboxing,Branchingandmerging.
Backupandrestorefilesaresavedastheyareedited.Onecanjumptoanymomentintime.
Synchronizationletsdeveloperssharefilesandstayuptodatewiththelatestversioneven
whiledevelopersareworkingsimultaneously.
ShorttermUndoallowstogobacktothelastknowngoodversioninthedatabase.
LongtermUndoforparticularlybadmistakestogobacklikeayearintimetofixabug.
TrackChanges,asfilesareupdatedyoucanleavecommentsastowhythechange
occurred.Thismakesiteasytoseehowafileisevolvingovertime,andwhy.Developers
shoulddocumentalmosteverychangetosourcecode.
TrackOwnership,aVCStagseverychangewiththenameofthepersonwhomadeit,
date/timeofchange.
Sandboxing,Insuranceagainstyourself,youcanmaketemporarychangesinanisolated
areaandtestandworkoutthekinksbeforecheckinginyourchanges
BranchingandMerging,Alargersandbox,youcanbranchacopyofyourcodeintoa
separateareaandmodifyitinisolation.Trackingchangesseparately.Lateryoucanmerge
yourworkbackintothecommonarea.
SetupTerms
Repository(repo):Thedatabasestoringthefiles.
Server:Thecomputerstoringtherepository
Client:Thecomputerconnectingtotherepository
WorkingSet/WorkingCopy:Yourlocaldirectoryoffiles,whereyoumakechanges.
Trunk/Main:Theprimarylocationforcodeintherepository,mainlineinatreeofcode.
BasicActions
Add:putafileintotherepositoryforthefirsttimetobegintrackingitwithversioncontrol
Revision:Whatversionafileison
Head:thelatestrevisionintherepository
Checkout:Downloadafilefromtherepository
Checkin:Uploadafiletotherepository(ifitchanged)
CheckinMessage:Ashortmessagedescribingwhatwaschanged
Changelog/History:Alistofchangesmadetoafilesinceitwascreated
Update/Sync:Synchronizeyourfileswiththelatestfromtherepository,thisletsyougrabthe
latestrevisionsofallfiles.
Revert:Throwawayyourlocalchangesandreloadthelatestversionfromtherepository.
AdvancedActions
Merge:Applythechangesfromonefiletoanother,tobringituptodate.Wecanmerge
featuresfromonebranchintoanother.
Conflict:Whenpendingchangestoafilecontradicteachother,bothchangescannotbe
applied.
Resolve:Fixingthechangesthatcontradicteachotherandcheckinginthecorrectversion.
Locking:Takingcontrolofafilesonobodyelsecanedititunityouunlockit.
BreakingtheLock:Forciblyunlockingafilesoyoucaneditit.
Checkoutforedit:Checkingoutaneditableversionofafile
TypesofVCSs
RCS:RevisionControlSystem,deadasastandalonesystem
CVS:ConcurrentVersionSystem,dyingnow.
Subversion:KillingCVS,opensourceunderApacheLicense.
Distributed/Decentralizedrevisioncontrol:GitandMercurial.Theyallowtheusertokeeptrack
ofsoftwarerevisionsandalsoallowmanydeveloperstoworkonaprojectfromdifferent
networks.
GNUBazaar
BitKeeper
GITCommonOperations
Settingupagitrepository
gitinit:initializesanewGitrepository.(firstcommandthatneedstobecalled)
gitclone?location:createsacopyofanexistingGitrepository.
gitadd?file:moveschangesfromtheworkingdirectorytothestagingarea.
gitcommit:takesthestagedsnapshotandcommitsittotheprojecthistory
gitpull:downloadsabranchfromaremoterepository,thenimmediatelymergesitintothe
currentbranch.
gitpush:movesalocalbranchtoanotherrepository.
_______________________________________________________________________
BindingProperty:enablesatargetobjecttobeboundtoasourceobject.Ifthevalueinthe
souceobjectchanges,thetargetpropertyisalsochangedautomatically.thetargetobjectis
simplycalledabindingobjectorabindingproperty.
**AGUIautomaticallykeepsitsdisplaysynchronizedwiththeapplicationsunderlyingdata:
abindingobservesitslistofdependenciesforchanges,andthenupdatesitselfautomatically
afterachangehasbeendetected**
/*TheStackPanelayoutpaneplacesallofthenodeswithinasinglestackwitheachnew
nodeaddedontopofthepreviousnode.Thislayoutmodelprovidesaneasywaytooverlay
textonashapeorimageandtooverlapcommonshapestocreateacomplexshape.*/
JavaFXExternalCSSstylefile:
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm())
LayoutPanes:JavaFXprovidesmanytypesofpanesfororganizingnodesinacontainer.
Event Programming
_________________________________________________________________
Foreachcontrol(button,combobox,etc.)wedefineaneventhandlerthatissimplyan
eventlistener.
AneventsourceisaGUIcontrolsuchasJButton,JComboBox,etc.Itcanregister
differenttypesoflisteners(handlers).
Whentheuserinteractswithacontrol(source):
aneventobjectisconstructed
theeventobjectissenttoallregisteredlistenerobjects
thelistenerobject(handler)respondsasyoudefineditto
YoucustomizetheresponseofaneventhandlerthroughInheritanceand
Polymorphism.
KindsofEventandListenerObjects
Differenteventsourcescanproducedifferentkindsofevents
ActionEvent(sentbyJButtonandothercomponents)
MouseEvent(sentbyJpanelandothercomponents)
Differentlistenerobjectsimplementdifferentrequiredmethodsfrominterfaces
ActionListener(actionPerformed)
MouseListener(mouseClicked,mouseEntered,mouseExited)
GUIDesignPattern
1)declareallGUIcontrolsasinstancevariables
2)Constructandarrange(layout)controls
3)Defineanclassforeachtypeofeventtobeyourlistener
4)Declareoneinstanceofeachhandlerasinstancevariables
5)Constructyourhandlerobjectsandgivethemwhattheyneed
6)RegisteryourhandlerswithyourGUIcontrols
ActionListenerInterface
Singlemethodintheinterface
publicvoidactionPerformed(ActionEvente)
TheActionEventclasshasmethodstogetinformationabouttheevent
publicObjectgetSource()
publicStringgetACtionCommand()
EventHandlingSummary
Specifyaclasstoimplementalistenerinterface,implementsActionListener
Codethatimplementsthemethodsofthelistenerinterface,publicvoid
actionPerformed(ActionEvente){..}
Codethatregistersalistenerobjectonaneventsource
cutButton.addACtionLister(this)
<html><Thisisthehtmltageveryhtmlpagehasone
<h1>heading,<p>paragraphtag
<h1id=header_id_1><youcanidentifytags
<tableborder=3>
<tr>
<td>..</td>
<td>..</td>
<td>..</td>
</tr>
</table>
HTMLwithJavaSwing
JButtonb1=newJButton("<html><b><u>T</u>wo</b><br>lines</html>")
b3=newJButton("<html><center><b><u>E</u>nable</b><br>"
+"<fontcolor=#ffffdd>middlebutton</font>",
rightButtonIcon)
LoadafileintoaHTMLDocumentobjectby
1)parsingthefile2)loadtheStringintoaeditorPane,3)thensetthetextofthepannel:
myEditorPane.setText(htmlText)
gettheHTMLDocumentfromthepannel:
doc=(HTMLDocument)test.myEditorPane.getDocument()
getHTMLelements:headerElement=doc.getElement("header_id_1")
setnewHTMLhtmlInnerString="<spanstyle=\"color:red\">thisish1</span>"
setthenewHTMLcodeinSWING:doc.setInnerHTML(headerElement,htmlInnerString)
Threads
_________________________________________________________________
WeusethreadsthatwedefinetomultitaskanduseathreadschedulethattheJVM
providesforus.
todefineyourownthreadsExtendjava.lang.Thread
youmakeyourthreadsrunnablei.e.startthem.Javasthreadschedulerdecidesthe
order.
newstate,notyetstartedthreadobject,notyetknowntothreadschedulernot
runnableasofyet
Newtorunnabletransition
Constructedthreadisstarted,callstartmethodonit,therecanbeseveral
threadsinthisstate.
RunnabletoBlockedTransition
Runnablethreadmadeunrunnable
callsleepmethodonitforXmillisecondsdirectlyorwithalockmethod
Cannotbescheduled
Again,theremaybemanythreadsinthisstate
Blockedtorunnabletransition
Unrunnablethreadmaderunnable
sleeptimeexpiresandisnotrenewed.unlockmethodensuresthis.
Canbescheduled
RunnabletoDeadtransition
Runmethodcompletes,cannotberescheduled.AdeadthreadisDead.
CallisAlivetotakeapulse.
start()
makesthethreadrunnable,callstherunmethod.Threadclassmethodalready
doesthis,ifyourclassextendsThreadyoudonthavetodefinestart.
run()
exectuedwhenathreadisstarted(withthemethodstart())
run()iswherethethreadworkisdone
theThreadsuperclassrunmethoddoesnothing
ifyourclassextendsThreadyoumustdefinerun()tospecifywhat
workyourthreadwilldo.
AnInterruptedExceptionisthrownwhenathreadiswaiting,sleeping,orotherwise
occupied,andthethreadisinterrupted,eitherbeforeorduringtheactivity.
Runnableinterface
has1method:run()
Alternativethreadingapproach:useimplementsRunnableANDdefinerun()
Staticyield()methodtemporarilyreleasestimeforotherthreads.
Sleep(longmillis)methodputsthethreadtosleepforthespecifiedtimeinmillis.
isAlive()
returnstrueifitisintheReady,Blocked,orRunningstate
returnsfalseifathreadisnewandhasnotstartedofitisfinishedinterrupt()
Theinterrupt()methodinterruptsathreadinthefollowingway:Ifathreadis
currentlyintheReadyorRunningstate,itsinterruptedflagissetifathreadis
currentlyblocked,itisawakenedandenterstheReadystate,andan
java.io.InterruptedExceptionisthrown.
TheisInterrupt()methodtestswhetherthethreadisinterrupted.
ThreadPriority
eachthreadisassignedadefaultpriorityofThread.NORM_PRIORITY
youcanresetthepriorityusingsetPriority(intpriority)
TomakeourframemultithreadedweimplementRunnable
GUIeventhandlingandpaintingcodeexecutesineventdispatchthread
Thisensuresthateacheventhandlerfinishesexecutingbeforethenextoneexecutes
andthepaintingisntinterruptedbyevents.
Killingathread
dontusestopmethod,letathreadkillitselfusingyourowninstancevariable
bymakingitaloopcontrolforrun
Forcountingusethreadorjava.util.Timerinstancetodothecounting
TimerTaskclass,weuseruntooverridetheworkdonebythethreadthatexecutesit.
Stacks vs Heap
_________________________________________________________________
Stack
Managedautomatically.
Stackvariablesonlyexistwhilethefunctionthatcreatedthem,isrunning
Heap
notmanagedautomaticallyforyou
youmustallocatethememoryontheheapyourself
doesnothavesizerestrictionsunlikethestack
variablescanbeaccessedglobally
>>>>>>
Javahasautomaticmemorymanagement
Asuserswemustknowhowtowriteoutprograms:
Callbyvalue:
thevalueiscopiedfromarguments(actualparametersintoreal
parameters)
Thereferencevariables(classinstances)containtheaddressofthe
objectontheheap.
Types
javaisstronglytypedlanguage,compiledcodeisguaranteedtobetypesafe
exceptforclasscasting
Typeabstraction
Thecomparableinterfaceprovidesastandardmeansforcommunicationwih
yetunknowntypesofobjectsusingcompareTo
ApparentvsActualType
Apparenttype
thetypeanobjectwasdeclaredas.Thecompilercaresabouthistype
Actualtype
typeanobjectwasconstructedas.theJVMcaresaboutthistype.
Personp=newStudent()
Apparent(left)Actual(Right)
declaredconstucted<<typeofvariable
compilerJVM<<whocares
Apparentvs.Actual
Apparentdatatypeofanobject,determineswhatmethodsmaybecalled
Actualdatatypedetermineswheretheimplementationofacalledmethodis
defined
JVMlooksfirstinactualtypeandworksitswayup.
Dynamicbinding
Dynamicbinding:isacomputerprogrammingmechanisminwhichthemethod
beingcalleduponanobjectislookedupbynameatruntime.
Callbyvalue
Javamethodsalwaysusecallbyvalue:
methodargumentsarecopiedwhensent
thisincludesobjectids
Interfaces
specifyabstractmethods
methodheaderswithnobodies
publicinterfaceEventHandler<Textendsevent>{
publicvoidhandle(Tevent)}
AclassimplementsEventHandlermustdefinehandle
elseasyntaxerror
SojavaFXknowntocallyoureventhandlershandle
AbstractClasses
canspecifyabstractandconcretemethods
An abstract method is that method which have only the initialization of
the method. only method name and its parameters. An abstract method
is in the abstract class with the "abstract" keyword.
While a concrete method is those method which is with the
implementation. means with definition.
Any class that extends an abstract class:
guarantees it will define all abstract methods
Interfaces/Abstract classes & Polymorphism
Objects can have an apparent type of
A concrete class
An interface
An abstract class
Objects can never have the actual type of an interface or abstract
class.
Interfaces/Abstract classes & Polymorphism
HAVE CONSTRUCTORS Y Y
CAN BE CONSTRUCTED Y
Staticsvs.NonStatic
Staticmethodsandvariablesarescopedtoaclass
onestaticvariableforallobjectstoshare
Nonstatic(object)methodsandvariablesarescopedtoasingleobject.
eachobjectsownsitsnonstaticmethodsandvariables.
Canastaticmethod
directlycallanonstaticmethodinthesameclasswiththe.NO
directlycallastaticmethodinthesameclass?Yes
directlyreferenceanonstaticvariableinthesameclass?No
directlyreferenceastaticvariableinthesameclass?True
Cananonstaticmethod
directlycallanonstaticmethodinthesameclasswiththe.Yes
directlycallastaticmethodinthesameclass?Yes
directlyreferenceanonstaticvariableinthesameclass?Yes
directlyreferenceastaticvariableinthesameclass?Yes
Inheritance
whenaclassisinherited,itgetsthemembers(fields,methods,andnested
classes)fromitssuperclassbutnotConstructors.Buttheconstructorofthe
superclasscanbeinvokedfromthesubclass.
AbstractClass
Anabstractclassisaclassthatisdeclaredabstractitmayormaynotinclude
abstractmethods.Abstractclassescannotbeinstantiated,buttheycanbe
subclassed.
Anabstractmethodisamethodthatisdeclaredwithoutanimplementation
(withoutbraces,andfollowedbyasemicolon),likethis
abstractvoidmoveTo(doubledeltaX,doubledeltaY)
Ifaclassincludesabstractmethods,thentheclassitselfmustbedeclared
abstract.
Whenanabstractclassissubclassed,thesubclassusuallyprovides
implementationsforalloftheabstractmethodsinitsparentclass.
WhatisanInterface?
Aninterfaceisagroupofrelatedmethodswithemptybodies
Abicycle'sbehavior,ifspecifiedasaninterface,mightappearasfollows:
interfaceBicycle{
//wheelrevolutionsperminute
voidchangeCadence(intnewValue)
voidchangeGear(intnewValue)
voidspeedUp(intincrement)
voidapplyBrakes(intdecrement)
}
Toimplementthisinterfaceaparticularclassmustimplementit
classACMEBicycleimplementsBicycle{
Implementinganinterfaceallowsaclasstobecomemoreformalaboutthebehaviorit
promisestoprovide.Interfacesformacontractbetweentheclassandtheoutsideworld,
andthiscontractisenforcedatbuildtimebythecompiler.Ifyourclassclaimstoimplement
aninterface,allmethodsdefinedbythatinterfacemustappearinitssourcecodebeforethe
classwillsuccessfullycompile.
Method overloading in Java occurs when two or more methods in the same class have the
exact same name but different parameters (remember that method parameters accept values
passed into the method).
Method overloading in Java occurs when two or more methods in the same class have the
exact
same
name
but
different parameters (remember that method parameters accept values passed into the
method).
Overriding methods is completely different from overloading methods. If a derived class
requires a different definition for an inherited method, then that method can be redefined in
the derived class.
Modifiers Accessibilities ^^
Binary I/O
_________________________________________________________________
Atextfileconsistsofasequenceofcharactersandabinaryfileconsistsofa
sequenceofbits.
BinaryI/Odoesnotrequireconversions:whenyouwriteabytetoafile,theoriginal
byteiscopiedintothefile,andwhenyoureadabytefromafile,theexactbyteinthe
fileisreturned.
TheSerializableInterface
notallobjectscanbewrittentoanoutputstream
Objectsthatcanbewrittentoanobjectstreamissaidtobeserializable.a
serializableobjectisaninstanceofthejava.io.Serializableinterface(sothe
classofaserializableobjectmustimplementSerializable).
theSerializableinterfaceisamarkerinterface:hasnomethods,soyou
donotneedtoaddadditionalcodeinyourclassthatimplements
Serializable.
TransientKeyword
youcantellJVMtoignorecertaindatafieldswhenwritingtoobjectstream.
RandomAccessFileclassallowsafiletobereadfromandwritetoatrandom
locations
Arandomaccessfileconsistsofasequenceofbytesandthereisaspecialmarker
calledfilepointerthatispositionedatoneofthesebytes
GENERICS
_________________________________________________________________
Itisbettertogetacompilingwarningthanaruntimeerror!
Genericsisthecapabilitytoparameterizetypes,basicallytellingwhattypeofthingsto
store.Forexampleastackobjectforholdingstrings.
Benefitofgenericsistoenableerrorstobedetectedatcompiletimeratherthen
runtime.
ifyouattempttousetheclassormethodwithanincompatibleobject,acompileerror
occurs.
Advantage:NoCastingNeeded
Backwardcompatibility:atechnologyisbackwardcompatibleifitcanworkwith
inputgeneratedforanoldertechnology
Forwardcompatibilityimpliesthatolddevicesallowinputformatsofnewdevicesto
run(withoutsupportingthenewfeatures).
Bottom-Up Development:
Top-Down Development:
AllmodulesthatusemoduleMareimplementedandtestedbeforeMisimplemented
Modulesthemselveswillprobablyusebottomupdevelopment
Canleadtoearliercompletionofusefulsubsystems.
Kinds of Testing
UnitTesting
testeachmoduleinaprogramseparately.
IntegrationTesting
Testinterfacesbetweenmodules
muchmoredifficultthanunittesting
RegressionTesting
Testprogramsaftermodificationstoensurecorrectbehavioroftheorignal
programispreserved.
Systemtesting
testoverallsystembehavior
Aspects of Testing
Howdowegeneratetestcases?
Exhaustive
considerallpossiblecombinationsofinputs
Sampled
Asmallbutrepresentativesubsetofallinputcombinations
Blackboxtesting:testcasesgeneratedfromprogram
specificationsandnotdependentontheimplementation
Glassboxtesting:testcasesgeneratedfromprogramscode
Blackboxtesting
itisthebestplacetostartwhenattemptingtotestaprogramthoroughly
testcasesbasedonprogramsspecifications,notonitsimplementation
testcasesarenotaffectedby:
invalidassumptionsmadebytheprogrammer
Implementationchanges
Testcasescanbegeneratedbyanindependentagent,unfamiliarwith
theimplementation.
Testcasesshouldcoverallpaths(notallcases)throughthe
specification,includingexceptions.
Boundary Conditions
isaninputthatisoneawayfromproducingadifferentbehaviorintheprogramcode
suchcheckscatch2commontypesoferrors:
logicalerrors,inwhichapathtohandleaspecialcasepresentedbya
boundaryconditionisomitted
Failuretocheckforconditionalsthatmaycausetheunderlyinglanguageor
hardwaresystemtoraiseanexception(ex:arithmeticoverlow)
Glass-box testing
Blackboxtestingisgenerallynotenough.
ForGlassboxtesting,thecodeofaprogrambeingtestedistakenintoaccount
Pathcompleteness
testcasesaregeneratedtoexerciseeachpaththroughaprogram.
maybeinsufficienttocatchallerrors
canbeusedeffectivelyonlyforaprogramfragmentthatcontainsareasonable
numberofpathstotest.
JUnit
Unittestframeworkforjavaprograms.
Thetestclasshasasetoftestmethods
publicvoidtestX()whereXisthemethodtobetested
Thetestmethodsuseassertionstoperformthetests,ex:
Assert.assertEquals(x,y)
Assert.assertTrue(c)
Notes on Assertions
Anassertionisajavastatementthatenablesyoutoassertanassumptionaboutyour
program
Anassertioncontainsabooleanexpressionthatshouldbetrueduringprogram
execution
Assertionscanbeusedtoassureprogramcorrectnessandavoidlogicerrors.
Declaring Assertions
AnassertionisdeclaredusingthenewJavakeywordassertasfollows
assertassertionsOR
assertassertion:detailMessage
WhereassertionisaBooleanexpressionanddetailMessageisaprimitivetypeoran
Objectvalue.
Executing Assertions
Whenanassertionstatementisexecuted,Javaevaluatestheassertion.
Ifitisfalse,anAssertionErrorwillbethrown.
Ithasanoargconstructoroftypeint,long,float,double,boolean,charand
Object.
AssertionErrorisasubclassofError,whenanassertionbecomesfalse,the
programdisplaysamessageontheconsoleandexits.
NotesfromDerekBanas
addschangesdynamically
Decoratordesignpatternsimplifiescodebecauseyouaddfunctionalityusingmany
simpleclassesratherthanrewritingoldcodeyoucanextendwithnewcode.
Wewanttobeabletowritenewcodetoaddfunctionalityinsteadofmodifyingold
code.
AboveWemakeapizzainterface,wemakeaconcreteclassofthemostbasicpizza.
ThenitgoestotempPizzawhichisthendecoratedbytheToppingDecorator
accordingly.
PizzabasicPizza=newTomatoSauce(newMozzarella(newPlainPizza()))
Soinsteadofmakinginfinitesubclasseswecanjusthavedecoratorswherewewrite
newcodebywritingnewclassestoincorporatenewbehaviorwithoutmodifying
existingcode.
^^^eachtimeanyEnermyAttackermethodiscalled,itcallsthecorrectversionwithin
EnemyRobotthusactinglikeanadapter.
Thispatternisusedwhenyouwanttotranslateoneinterfaceofaclassintoanotherinterface.Now,
itmakessensethatthese2interfacesarecompatibleotherwisethepatternmaynotmakesense.
Toaccomplishthis,allyouneedtodoisbridgethedifferencesusingouroldfriendcomposition
again.
Existingsystemusesadriverviaaninterface.
Newhardwareusesadifferentinterface
adaptercanadaptdifferences
ExistingsystemHASAOldInteface
AdapterimplementsOldInterfaceandHASANewInterface
ExistingsystemcallsOldInterfacemethodsonadapter,adapterforwardsthemtoNewInterface
implementations.
Employstheprincipleofleastknowledge
FromLiang,TheFacadepatternprovidesaunifiedinterfacetoasetofinterfacesina
subsystem.Facadedefinesahigherlevelinterfacethatmakesthesubsystemeasier
touse.BeforeapplyingtheFacadepattern,asubsystemmaylookliketheonein
Figure6(a)wherethecomponentsareaccessedbymany500clients.Applyingthe
Facadepattern,youcancreateaunifiedinterfacecalledFacade,asshowninFigure
6(b),wheretheclientsaccessthecomponentsinthesubsystemthroughtheFacade.
Usedwhenyouneedtocreatealargelargenumberofsimilarobjects
toreducememoryusageyoushareObjectsthataresimilarinsomewayratherthan
creatingnewones
theycanallbecontrolledidentically.
IntrinsicState:Color,whatiscommonamongobjects
ExtrinsicState:Size,Whatvariesbetweenobjects
Flyweightisbeneficialbecauseitreducesthenumberofobjectinstancesatruntime,
savingmemory.Italsocentralizesstateformanyvirtualobjectsintoasinglelocation.
Onceyouhaveimplementedit,single,logicalinstancesoftheclasswillnotbeableto
behaveindependentlyfromtheotherinstances.
Mustbeimmutable
Dependonanassociatedtable
mapsidenticalinstancestothesingleobjectthatrepresentsallofthem
Separatesanobjectsinterfacefromitsimplementation
FromLiang
TheBridgepatternallowsyoutovarytheimplementationandtheabstraction
byplacingthetwoinseparateclasshierarchies.
Scenario
youarewritingthecodeforanewergonomicanduserfriendlyremotecontrol
forTVs.
therewillbelotsofimplementationsoneforeachmodelofTVusean
abstraction(interface)
youknowtherewillbemanychangesovertimetothespecificationneedsto
accommodatechanges
Solution?Abstracttheabstraction.
Benefits
Abstractionandimplementationcanbeextendedindependently
Changestotheconcreteabstractionclassesdonotaffecttheclient.
Factoriesmakestuff,factoryclassesmakeobjects.
Factoryclassesemployconstructors
Whyusefactorypattern?
Factorypatternpreventsmisuse
hidesconstruction
provideapiconvenience
onestopshopforgettinganobjectofafamilytype
Whatobjectsdofactoriesmake?
commonancestor
sameapparenttype
differentactualtype
FactorypatternAdvantages
programusingfactorydesignpatternneverneedstoknowabouttheactual
class/type.
simplifiesuseforprogrammer
fewerclassestolearn
FromLiang
Thefactorymethodpatterndefinesanabstractmethodforcreatinganobject,
butletsubclassesdecidewhichclasstoinstantiate.Factorymethodletsa
classdeferinstantiationtosubclasses.
Example
BorderFactory.createXXXBordermethods
returnapparenttypeofinterfaceBorder
returnactualtypesofBevelBorder,EtchedBorder,etc
FromLiang,Thesingletonpatterndeclaresaclassthatcanbeusedtoinstantiatea
uniqueinstance.Occasionally,itisdesirabletorestrictinstantiationofaclassto
exactlyoneobject.Forexample,theremaybemanyprintersinasystem,butthere
shouldbeonlyoneprinterspooler.
So,yousystemshouldensurethatonlyoneprinterspoolerobjectiscreated
Thesingletonpatterncanbeimplementedbycreatingaclasswithaprivate
constructorandastaticconstantthatreferencesaninstanceoftheclass.
Singletonshouldbeconsideredonlyifallthreeofthefollowingcriteriaaresatisfied:
ownershipofthesingleinstancecannotbereasonablyassigned
LazyInitializationisdesirable
Globalaccessisnototherwiseprovidedfor
Example
TheSingletonpatternensuresthataclasshasonlyoneinstanceandprovides
aglobalpointofaccesstothatinstance.Itisnamedafterthesingletonset,
whichisdefinedtobeasetcontainingoneelement.TheofficeofthePresident
oftheUnitedStatesisaSingleton.TheUnitedStatesConstitutionspecifiesthe
meansbywhichapresidentiselected,limitsthetermofoffice,anddefinesthe
orderofsuccession.Asaresult,therecanbeatmostoneactivepresidentat
anygiventime.Regardlessofthepersonalidentityoftheactivepresident,the
title,"ThePresidentoftheUnitedStates"isaglobalpointofaccessthat
identifiesthepersonintheoffice.
Allowsconstructioninsteps,goodforcomplexobjectconstruction.
Examplescenario,buildavacationplannerforathemepark
Guestscanchooseahotel,tickets,events,etc.
guestsmaywantzerotomanyofeach
createaplannertoencapsulateallthisinformation
FromDerekBanas
Builderpatternisapatternusedtobuildanobjectmadeupfromotherobjects
whenyouwantthecreationofthesepartstobeindependentofthemainobject
hidethecreationofthepartsfromtheclientsobotharenotdependent
builderknowsthespecificsandnobodyelsedoes
Example
TheBuilderpatternseparatestheconstructionofacomplexobjectfromits
representationsothatthesameconstructionprocesscancreatedifferent
representations.Thispatternisusedbyfastfoodrestaurantstoconstruct
children'smeals.Children'smealstypicallyconsistofamainitem,asideitem,
adrink,andatoy(e.g.,ahamburger,fries,Coke,andtoydinosaur).Notethat
therecanbevariationinthecontentofthechildren'smeal,buttheconstruction
processisthesame.Whetheracustomerordersahamburger,cheeseburger,
orchicken,theprocessisthesame.Theemployeeatthecounterdirectsthe
crewtoassembleamainitem,sideitem,andtoy.Theseitemsarethenplaced
inabag.Thedrinkisplacedinacupandremainsoutsideofthebag.This
sameprocessisusedatcompetingrestaurants.
Builderreturnstheproductasafinalstepafterbuildingitinparts.
Helpsuseasilycreatenewobjectsthroughcloning,thenewobjectswouldinfacthave
differentaddressstoredinmemory.
theprototypespecifiesthekindofobjectstobecreated.
Toenableanobjecttobecloned,theclassmustimplementtheCloneableinterface
andoverridetheclone()method.
PrototypeBenefits
hidesthecomplexitiesofmakingnewinstancesfromtheclient
providestheoptionfortheclienttogenerateobjectswhosetypeisnotknown
Insomeinstancescopyinganobjectismoreefficientthancreatinganew
object.
PrototypeUsesandDrawbacks
Prototypeshouldbeconsideredwhenasystemmustcreatenewobjectsof
manytypesinacomplexclasshierarchy
Adrawbacktousingtheprototypeisthatmakingacopyofanobjectcan
sometimesbecomplicated.
Designpatternsthatidentifycommoncommunicationspatternsbetweenobjectsand
realizethesepatterns.
Theyincreasetheflexibilityincarryingoutcommunication
1. Strategypattern:algorithmscanbeselectedonthefly
2. Templatemethodpattern:describestheprogramskeletonofaprogram
3. Observerpattern:objectsregistertoobserveaneventthatmayberaisedbyanother
object.
4. Commandpattern:commandobjectsencapsulateanactionanditsparameters
5. Iteratorpattern:iteratorsareusedtoaccesstheelementsofanaggregateobject
sequentiallywithoutexposingitsunderlyingrepresentation
6. Statepattern:acleanwayforanobjecttopartiallychangeitstypeatruntime.
Definesafamilyofalgorithms,encapsulateeachone,andmakethem
interchangeable.Strategyletsthealgorithmvaryindependentlyfromtheclientsthat
useit.
Capturetheabstractioninaninterface,buryimplementationdetailsinderivedclasses.
Example:AStrategydefinesasetofalgorithmsthatcanbeusedinterchangeably.
ModesoftransportationtoanairportisanexampleofaStrategy.Severaloptionsexist
suchasdrivingone'sowncar,takingataxi,anairportshuttle,acitybus,ora
limousineservice.Forsomeairports,subwaysandhelicoptersarealsoavailableasa
modeoftransportationtotheairport.Anyofthesemodesoftransportationwillgeta
travelertotheairport,andtheycanbeusedinterchangeably.Thetravelermustchose
theStrategybasedontradeoffsbetweencost,convenience,andtime.
Template Method Design Pattern
_________________________________________________________________
Atemplateforanalgorithm
Definestheskeletonofanalgorithminamethod,deferringsomestepstosubclasses.
Letssubclassesredefinecertainstepsofanalgorithmwithoutchangingthe
algorithmsstructure.
Example
Whats a hook
_________________________________________________________________
Atypeofaconcretemethod
Declaredintheabstractclass
onlygivenanemptyordefaultimplementation
Givessubclassestheabilitytohookintothealgorithmatvariouspoints,iftheywish.
Asubclassisalsofreetoignorethehook.
Strategy
subclassesdecidehowtoimplementstepsinalgorithm
Templatemethod
encapsulateinterchangeablebehaviorsandusedelegationtodecidewhich
behaviortouse
Definesaonetomanydependencybetweenobjectssothatwhenoneobjectchanges
state,allitsdependentsarenotifiedandupdatedautomatically.
FromLiang,Theobserverpatterndefinesadependencyrelationshipbetweenan
Object(calledsubject)anditsdependentobjects(calledobservers).Whenthesubject
objectchangesitsstate,alltheobserversobjectsarenotified.
WeseethisinourGUI
example,TheObserverdefinesaonetomanyrelationshipsothatwhenoneobject
changesstate,theothersarenotifiedandupdatedautomatically.Someauctions
demonstratethispattern.Eachbidderpossessesanumberedpaddlethatisusedto
indicateabid.Theauctioneerstartsthebidding,and"observes"whenapaddleis
raisedtoacceptthebid.Theacceptanceofthebidchangesthebidpricewhichis
broadcasttoallofthebiddersintheformofanewbid.
MVC employs the observer pattern
_________________________________________________________________
Model
notifiesviewswhensomethinginterestinghappens
View/Observer
Visualrepresentation
viewsattachthemselvestomodelinordertobenotified
Controller
eventhandler
listenersthatareattachedtoviewinordertobenotifiedofuserinteraction
MVCInteraction
controllerupdatesmodel
modeltellsviewthatdatahaschanged
viewredrawn
Encapsulatearequestasanobject,therebylettingyouparameterizeclientswith
differentrequests,queueorlogrequests,andsupportundoableoperations.
Anobjectorientedcallback
TheCommandpatternallowsrequeststobeencapsulatedasobjects,thereby
allowingclientstobeparameterizedwithdifferentrequests.The"check"atadineris
anexampleofaCommandpattern.Thewaiterorwaitresstakesanorderorcommand
fromacustomerandencapsulatesthatorderbywritingitonthecheck.Theorderis
thenqueuedforashortordercook.Notethatthepadof"checks"usedbyeachwaiter
isnotdependentonthemenu,andthereforetheycansupportcommandstocook
manydifferentitems.
SequentiallyaccesstheelementsofaCollection
Providesaunifiedwayfortraversingandprocessingtheelementsinanaggregate
objectsuchasanarray,set,list,andmapwithoutexposingitsunderlying
representation.
Aniteratorisaseparateobjectthatcontainsthemethodforretrievingandprocessing
theelementsintheaggregateobject.
Iteratorsarecommonlydefinedusinganinterface.
TheIteratorprovideswaystoaccesselementsofanaggregateobjectsequentially
withoutexposingtheunderlyingstructureoftheobject.Filesareaggregateobjects.In
officesettingswhereaccesstofilesismadethroughadministrativeorsecretarialstaff,
theIteratorpatternisdemonstratedwiththesecretaryactingastheIterator.Several
televisioncomedyskitshavebeendevelopedaroundthepremiseofanexecutive
tryingtounderstandthesecretary'sfilingsystem.Totheexecutive,thefilingsystemis
confusingandillogical,butthesecretaryisabletoaccessfilesquicklyandefficiently.
Onearlytelevisionsets,adialwasusedtochangechannels.Whenchannelsurfing,
theviewerwasrequiredtomovethedialthrougheachchannelposition,regardlessof
whetherornotthatchannelhadreception.Onmoderntelevisionsets,anextand
previousbuttonareused.Whentheviewerselectsthe"next"button,thenexttuned
channelwillbedisplayed.Considerwatchingtelevisioninahotelroominastrange
city.Whensurfingthroughchannels,thechannelnumberisnotimportant,butthe
programmingis.Iftheprogrammingononechannelisnotofinterest,theviewercan
requestthenextchannel,withoutknowingitsnumber.
Statepatternallowsanobjecttoalteritsbehaviorwhenitsinternalstatechanges.The
objectwillappeartochangeitsclass.Theobjectrepresentsastate.Itisautomatically
changedtoanewstateobjectwhenthestatechanges.
Thestatepatternstructurecanbeoutlinedasshowbelow
Thestatepatternusesobjectstorepresentstates.
Example,The State pattern allows an object to change its behavior
when its internal state changes. This pattern can be observed in a
vending machine. Vending machines have states based on the
inventory, amount of currency deposited, the ability to make change,
the item selected, etc. When currency is deposited and a selection is
made, a vending machine will either deliver a product and no
change, deliver a product and change, deliver no product due to
insufficient currency on deposit, or deliver no product due to
inventory depletion.
Code Profiling
__________________________________________________________________________
Programsshould
solveaproblemcorrectly,bereadable,beflexibleforfuturemodifications,be
fastandbelean(usetheleastamountofmemorynecessary).
Hardwarebecomesfasterandmorecapable,butdataismore.
programefficiencyisstillanissue
softwareexpectationscontinuetoincrease
Whennottooptimize(makethebestormosteffectiveuseof)
Onlyoptimizewhennecessary
Whynotjustberesponsibleandalwaysoptimize?
Optimizationisagoodwaytointroducebugs
sometechniquesdecreasetheportabilityofyourcode
youcanexpendalotofeffortforlittleornotresults
optimizationmakesthecodelessreadable!
increasescomplexityandthedifficultyofdebugging
optimizationcanbehardtodoproperly
optimizationisamovingtarget
Sowhatisoptimizing?
Modifyingasystemtoimproveitsperformance
WhydoesDonaldKnuthhateit?
becausealltheoptimizationintheworldcanneverreplacethewiseselection
ofproperdatastructuresandtheproperuseofefficientalgorithms.
Optimizationoptions
Designforspeed:selectyourdatastructuresandalgorithmswisely
Useacodeprofiler
userautomaticoptimizers
Implementlowlevelcodeoptimizations
Intheprocessofdesigningaprogram:
Identifyoperationsneededineachclassbeforechoosingyourdata
structures
pickadatastructurethatcanbeusedtoperformsuchoperations
efficiently
Selectasolidalgorithmthatfitstheproblemandthedata:BigO
notation
ProgramHotSpots
Whenthechoiceofbestdatastructureofalgorithmisnotclearatdesigntime:
usethesimplestdatastructureoralgorithm,collectdataabouttheimpactof
thedatastructureofalgorithmontheoverallspeedoftheprogram.
Identifytheportionofthecodethattakesthemosttimeormemory
Replacethatsection,ifpossiblewithabetterstructureofalgorithm.
Whatsaprofile?
Aprofilerisaprogramthatcantacktheperformanceofanotherprogramby
checkinginformationcollectedwhilethecodeisexecuting:
canusuallytracktimeusedorfrequencyofuseofcode(random
samplingwithaparllelthread)
theentireapplicationorjustselectmethods
Typesofprofiling
CPUperformanceprofiling
memoryprofiling
Threadsprofiling
memoryleakprofiling
CollectingperformancedatausingHProf
Generateprofiledataonsampleruns
javaclassicXrunhprofDriver
javaclassicXrunhprof:cpu=samplesDriver
Analyzetheprofiledatatofind
hotspotswithrespecttotime
mostfrequentlyusedmethods
mosttimeconsumingmethods
bottlenecks
hotspotswithrespecttospace(memory)
mostfrequentlyusedportionsofdatastructures
AdditionalOptimizationtools
Compileralreadyperformmanyoptimizations
javacO,thejavaoptimizer
Optimizescompiledcodebyliningstatic,finalandprivatemethods.
Inliningamethodcallinsertsthecodeforthemethoddirectlyintothe
codemakingthemethodcall
Eliminatestheoverheadofthemethodcall
forasmallmethodthisoverheadcanrepresentasignificant
percentageofitsexecutiontime
Onlyprivate,static,orfinalmethodsareeligibleforinling
Synchronizedmethodswontbeinlined
Thecompilerwillonlyinlinesmallmethods
MachineCode
javaccompilesjavaprogramstothemachinecodefortheJVM
directlycallingthiscodecanimproveprogramperformance
javapctodumpouttheJVMinstructionsgeneratedbytheJavacompiler
gccStodumpassemblyinstructionsgeneratedbytheCcompiler
JNI
JavaNativelanguageInterface
Standardprogramminginterfaceforwritingjavanativemethodsand
embeddingtheJavavirtualmachineintonativeapplications
LookupTables
Precomputedvaluesofsomecomputationthatyouknowyouwillperform
duringruntime
simplycomputeallpossiblevaluesatstartupthenrunthegame
OptimizationGuidelines
DoNOThandoptimizeyourcode:
Ifitunnecessarilysacrificesreadability,OR
ifitunnecessarilysacrificesmaintainability
Ifanoptimizationisnecessary,thinkdatastructuresandalgorithmsfirst
Manycommoncodeoptimizationsaredonebythecompiler
Don'toveroptimize
Annotations
__________________________________________________________________________
Featuresofsomelanguages
programmerconveniences
Usefulincheckinginheritance
alternatedevelopmentmodes
@Override
RememberJUnit?
@Before,@After,@Test
@isJavasnotationforthestartofanannotation
like@authorforjavadoc
Whatarethey?
metadata,providedataaboutaprogram
Whatareannotationsusedfor?
Informationforthecompilertodetecterrorandtosuppresswarnings.
Compiletimeanddeploymenttimeprocessing
forIDEsandothertools
generatecode,XMLfiles,etc.
Runtimeprocessing
someannotationsareusedatruntime
Annotationscanhavefieldnamesanddata
@author(name=bob,date=3/27/2003)
Wherecanannotationsbeused?
Declarationsofclasses,fields,methods,etc.
JavaSE8alsohastypeannoations:
Classinstancecreationexpressions:
new@InternedMyObject()
Typecast:myString=(@NonNullString)str
implementsclause:
classUnmodifiableList<T>implements@ReadonlyList<@readonly
T>{.....}
Thrownexceptiondeclaration
voidmonitorTemperature()throws@CriticalTemperatureException{..}
Whydowecareaboutannotations?
Toolslovetousethem
JUnit,Javadoc,Webrelatedtools
Annotationstypes
Thepredefinedannoationtypesdefinedinjava.langare@Deprecated,
@Override,and@SuppressWarnings
@Deprecatedannotationindicatesthatthemarkedelementis
deprecatedandshouldnolongebeused.
DeclaringanAnnotationType
@interfaceClassPreamble{
Stringauthor()
Stringdate()
intcurrentRevision()default1
String[]reviewers().}
Aftertheannotationtypeisdefined,youcanuseannotationsofthat
type
@ClassPreamble(reviewers={Alice,bob}
DeclaringanAnnotationType
Tomaketheinformationin@ClassPreambleappearin
javadocgenerateddocumentation,whenyoudefinetheannotation
Reflection
Apowerfulprogrammingfeature
requirestheabilitytoexamineormodifytheruntimebehaviorof
applicationsrunningintheJavaVirtualMachine.
Dynamicallyexamineclassesandobjects
shouldbeusedonlybydeveloperswhohaveastronggraspofthe
fundamentalofthelanguage.
Callmethodsatruntimethatyoudidnotknowexistedatcompiletime
Atruntime:askaclasswhatmethodithas,calloneofthosemethods
ReflectionUses
Extensibilityfeatures
dynamicallyuseclassesnotknownatcompiletime,plugins,
addons,etc.completeflexibility.
Reflection
ItallstartswiththeClassclass:
Everyobjectinjavaisamemberofaclass.
getClass()methodinheritedfromObject
example,Classc=Hello.getClass()
itcouldthrowClassNotFoundException
othermethodsinclude
getSuperclass
getDeclaredClasses
Fields
Hasatypeandvalue
TypeisaClass
get/setdataviaget/setmethods
Otherusefulclasses
method
constructor
DrawbacksofReflection
PerformanceOverhead
dynamictyperesolutionisexpensive
certainjavavirtualmachineoptimizationsskipped
shouldbeavoidedinhotspots
SecurityRestrictions
ExposeofInternals.