[PDF] design patterns in java with real life examples
[PDF] design patterns in ooad pdf
[PDF] design patterns in swift 5
[PDF] design patterns in swift medium
[PDF] design patterns interview questions
[PDF] design patterns ios
[PDF] design patterns java
[PDF] design patterns lecture notes
[PDF] design patterns midterm exam
[PDF] design patterns pdf github
[PDF] design patterns quiz questions
[PDF] design patterns tutorial for beginners
[PDF] design patterns tutorials point pdf
[PDF] design patterns: elements of reusable object oriented software epub
[PDF] design process
Javadesign patterns101
Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Tableof Contents
Ifyou're viewingthisdocument online,youcan clickanyof thetopicsbelow tolinkdirectly tothatsection.
1.About thistutorial.......................................................2
2.Design patternsoverview.............................................4
3.A briefintroductionto UMLclassdiagrams ........................8
4.Creational patterns.....................................................10
5.Structural patterns......................................................12
6.Behavioral patterns....................................................15
7.Concurrency patterns..................................................18
8.Wrapup ...................................................................20
Javadesign patterns101Page 1of22
Section1. Aboutthistutorial
ShouldI takethistutorial?
Thistutorial isforJava programmerswhowant tolearnabout designpatternsas ameansof improvingtheir object-orienteddesignand developmentskills.After readingthistutorial you will: *Understand whatdesignpatterns areandhow theyaredescribed andcategorizedin severalwell-known catalogs *Be abletouse designpatternsas avocabularyfor understandinganddiscussing object-orientedsoftware design *Understand afewof themostcommon designpatternsand knowwhenand howthey shouldbe used Thistutorial assumesthatyou arefamiliarwith theJavalanguage andwithbasic object-orientedconcepts suchaspolymorphism, inheritance,andencapsulation. Some understandingof theUnifiedModeling Language(UML)is helpful,butnot required;this tutorialwill provideanintroduction tothebasics.
Whatis thistutorialabout?
Designpatterns capturetheexperience ofexpertsoftware developers,andpresent common recurringproblems, theirsolutions,and theconsequencesof thosesolutionsin methodical way.
Thistutorial explains:
*Why patternsareuseful andimportantfor object-orienteddesignand development *How patternsaredocumented, categorized,andcataloged *When patternsshouldbe used *Some importantpatternsand howtheyare implemented Tools Theexamples inthistutorial areallwritten intheJava language.Itis possibleandsufficient toread thecodeas amentalexercise, buttotry outthecode requiresaminimal Java developmentenvironment. Asimpletext editor(suchas NotepadinWindows orviin aUNIX environment)and theJavaDevelopment Kit(version1.2 orlater)are allyouneed. Anumber oftoolsare alsoavailablefor creatingUMLdiagrams (seeResourcesonpage 20).
Theseare notnecessaryfor thistutorial.
Aboutthe author
Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 2of22
DavidGallardo isanindependent softwareconsultantand authorspecializingin software internationalization,Java Webapplications,and databasedevelopment.He hasbeena professionalsoftware engineerforover 15yearsand hasexperiencewith manyoperating systems,programming languages,andnetwork protocols.Davidmost recentlyleddatabase andinternationalization developmentata business-to-businesse-commercecompany, TradeAccess,Inc. Priortothat, hewasa seniorengineerin theInternationalProduct Developmentgroup atLotusDevelopment Corporation,wherehe contributedtothe developmentof across-platformlibrary providingUnicodeand internationallanguagesupport forLotus productsincludingNotes and1-2-3.
Youcan contactDavidat david@gallardo.org.
Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 3of22
Section2. Designpatternsoverview
Abrief historyofdesign patterns
Designpatterns werefirstdescribed byarchitectChristopher Alexanderinhis bookAPattern Language:Towns, Buildings,Construction(OxfordUniversity Press,1977).The concepthe introducedand calledpatterns--abstracting solutionstorecurring designproblems-- caught theattention ofresearchersin otherfields,especially thosedevelopingobject-oriented softwarein themid-to-late1980s. Researchinto softwaredesignpatterns ledtowhat isprobablythe mostinfluentialbook on object-orienteddesign: DesignPatterns: ElementsofReusable Object-OrientedSoftware, byErich Gamma,RichardHelm, RalphJohnson,and JohnVlissides(Addison-Wesley, 1995; seeResourcesonpage 20).These authorsareoften referredtoas the"Gangof Four"and thebook isreferredto astheGang ofFour(or GoF)book. Thelargest partofDesignPatterns isa catalogdescribing23 designpatterns.Other, more recentcatalogs extendthisrepertoire andmostimportantly, extendcoverageto more specializedtypes ofproblems.Mark Grand,inPatternsin Java:ACatalog ofReusable DesignPatterns IllustratedwithUML ,adds patternsaddressingproblems involving concurrency,for example,andCoreJ2EE Patterns:BestPractices andDesignStrategies by DeepakAlur, JohnCrupi,and DanMalksfocuses onpatternsfor multi-tierapplicationsusing
Java2 enterprisetechnologies.
Thereis anactivepattern communitythatcollects newpatterns,continues research,and takesleads inspreadingthe wordonpatterns. Inparticular,the HillsideGroupsponsors manyconferences includingoneintroducing newcomerstopatterns undertheguidance of experts.Resourcesonpage 20providesadditional sourcesofinformation aboutpatternsand thepattern community.
Piecesof apattern
TheGang ofFourdescribed patternsas"a solutiontoa problemina context".Thesethree things-- problem,solution,and context--are theessenceof apattern.For documentingthe patternit isadditionallyuseful togivethe patternaname, toconsiderthe consequences usingthe patternwillhave, andtoprovide anexampleor examples. Differentcatalogers usedifferenttemplates todocumenttheir patterns.Differentcatalogers alsouse differentnamesfor thedifferentparts ofthepattern. Eachcatalogalso varies somewhatin thelevelof detailandanalysis devotedtoeach pattern.Thenext severalpanels describethe templatesusedin DesignPatterns andin Patternsin Java.
DesignPatterns template
DesignPatterns usesthe followingtemplate:
*Pattern nameandclassification: Aconceptualhandle andcategoryfor thepattern *Intent: Whatproblemdoes thepatternaddress? Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 4of22
*Also knownas:Other commonnamesfor thepattern *Motivation: Ascenariothat illustratestheproblem *Applicability: Inwhatsituations canthepattern beused? *Structure: Diagramusingthe ObjectModelingTechnique (OMT) *Participants: Classesandobjects indesign *Collaborations: Howclassesand objectsinthe designcollaborate *Consequences: Whatobjectivesdoes thepatternachieve? Whatarethe tradeoffs? *Implementation: Implementationdetailsto consider,language-specificissues *Sample code:Samplecode inSmalltalkand C++ *Known uses:Examplesfrom therealworld *Related patterns:Comparisonand discussionofrelated patterns
Patternsin Javatemplate
Patternsin Javausesthe followingtemplate:
*Pattern Name:Thename andareference towhereit wasfirstdescribed *Synopsis: Averyshort descriptionofthe pattern *Context: Adescriptionof theproblemthe patternisintended tosolve *Forces: Adescriptionof theconsiderationsthat leadtothe solution *Solution: Adescriptionof thegeneralsolution *Consequences: Implicationsofusing thepattern *Implementation: Implementationdetailsto consider *Java APIUsage:When available,anexample fromtheJava APIismentioned *Code example:Acode exampleinthe Javalanguage *Related patterns:Alist ofrelatedpatterns Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 5of22
Learningpatterns
Themost importantthingsto learnatfirst istheintent andcontextof eachpattern:what problem,and underwhatconditions, thepatternis intendedtosolve. Thistutorialcovers someof themostimportant patterns,butskimming throughafew catalogsandpicking out thisinformation abouteachpattern istherecommended nextstepfor thediligentdeveloper. InDesignPatterns, therelevant sectionstoread are"Intent,""Motivation," andApplicability." InPatternsin Java,therelevant sectionsare"Synopsis," "Context,"and"Forces and
Solution."
Doingthe backgroundresearchcan helpyouidentify apatternthat lendsitselfas asolution toa designproblemyou're facing.Youcan thenevaluatethe candidatepatternmore closely forapplicability, takingintoaccount thesolutionand itsconsequencesin detail.Ifthis fails, youcan looktorelated patterns. Insome cases,youmight findmorethan onepatternthat canbeused effectively.Inother cases,there maynotbe anapplicablepattern, orthecost ofusingan applicablepattern,in termsof performanceorcomplexity, maybetoo high,andan adhoc solutionmay bethe bestway togo.(Perhaps thissolutioncan leadtoa newpatternthat hasnotyet been documented!)
Usingpatterns togainexperience
Acritical stepindesigning object-orientedsoftwareis discoveringtheobjects. Thereare varioustechniques thathelp:use cases,collaborationdiagrams, or Class-Responsibility-Collaboration(CRC) cards,forexample --butdiscovering theobjectsis thehardest stepforinexperienced designerstoget right. Lackof experienceorguidance canleadto toomanyobjects withtoomany interactionsand thereforedependencies, creatingamonolithic systemthatis hardtomaintain andimpossible toreuse. Thisdefeatsthe aimofobject-oriented design. Designpatterns helpovercomethis problembecausethey teachthelessons distilledfrom experienceby experts:patternsdocument expertise.Further,patterns notonlydescribe how softwareis structured,butmore importantly,theyalso describehowclasses andobjects interact,especially atruntime. Takingtheseinteractions andtheirconsequences explicitly intoaccount leadstomore flexibleandreusable software.
Whennot tousepatterns
Whileusing apatternproperly resultsinreusable code,theconsequences ofteninclude somecosts aswellas benefits.Reusabilityis oftenobtainedby introducingencapsulation,or indirection,which candecreaseperformance andincreasecomplexity. Forexample, youcanuse theFacadepattern towraploosely relatedclasseswith asingle classto createasingle setoffunctionality thatiseasy touse.One possibleapplicationmight beto createafacade fortheJava InternationalizationAPI.This approachmightbe reasonablefor astand-aloneapplication, wheretheneed toobtaintext fromresource bundles,format datesandtime, andsoon, isscatteredin variouspartsof theapplications. Butthis maynotbe soreasonablefor amultitierenterprise applicationthatseparates Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 6of22
presentationlogic frombusiness.If allcallsto theInternationalizationAPI areisolatedin a presentationmodule --perhapsby wrappingthemas JSPcustomtags --itwould be redundantto addyetanother layerofindirection. Anotherexample ofwhenpatterns shouldbeused withcareis discussedinConcurrency patternsonpage 18,regarding theconsequencesof theSingleThread Executionpattern. Asa systemmatures,as yougainexperience, orflawsin thesoftwarecome tolight,it's good tooccasionally reconsiderchoicesyou've madepreviously.You mayhaveto rewriteadhoc codeso thatituses apatterninstead, orchangefrom onepatternto another,orremove a patternentirely toeliminatea layerofindirection. Embracechange(or atleastprepare forit) becauseit's inevitable. Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 7of22
Section3. Abriefintroduction toUMLclass diagrams
Classdiagrams
UMLhas becomethestandard diagrammingtoolfor object-orienteddesign.Of thevarious typesof diagramsdefinedby UML,thistutorial onlyusesclass diagrams.Inclass diagrams, classesare depictedasboxes withthreecompartments: Thetop compartmentcontainsthe classname;if theclassis abstractthename isitalicized. Themiddle compartmentcontainsthe classattributes(also calledproperties,or variables). Thebottom compartmentcontainsthe classmethods(also calledoperations).Like theclass name,if amethodis abstract,itsname isitalicized. Dependingon thelevelof detaildesired,it ispossibleto omittheproperties andshowonly theclass nameandits methods,orto omitboththe propertiesandmethods andshowonly theclass name.Thisapproach iscommonwhen theoverallconceptual relationshipisbeing illustrated.
Associationsbetween classes
Anyinteraction betweenclassesis depictedbya linedrawnbetween theclasses.A simple lineindicates anassociation,usually aconceptualassociation ofanyunspecified type.The linecan bemodifiedto providemorespecific informationaboutthe association.Navigability isindicated byaddingan openarrowhead.Specialization,or subclassing,isindicated by addinga triangulararrowhead.Cardinal numbers(oran asteriskforan unspecifiedplurality) canalso beaddedto eachendto indicaterelationships,such asone-to-oneand many-to-one. Thefollowing diagramsshowthese differenttypesof associations: Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 8of22
Resourcesonpage 20providesfurther readingonUML andJavalanguage associations. Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 9of22
Section4. Creationalpatterns
Overview
Creationalpatterns prescribethe waythatobjects arecreated.These patternsareused whena decisionmustbe madeatthe timeaclass isinstantiated.Typically, thedetailsof the classesthat areinstantiated-- whatexactlythey are,how,and whentheyare created--are encapsulatedby anabstractsuperclass andhiddenfrom theclientclass, whichknowsonly aboutthe abstractclassor theinterfaceit implements.Thespecific typeofthe concreteclass istypically unknowntothe clientclass. TheSingleton pattern,forexample, isusedto encapsulatethecreation ofanobject inorder tomaintain controloverit. Thisnotonly ensuresthatonly oneiscreated, butalsoallows lazy instantiation;that is,theinstantiation oftheobject canbedelayed untilitis actuallyneeded. Thisis especiallybeneficialif theconstructorneeds toperforma costlyoperation,such as accessinga remotedatabase.
TheSingleton pattern
Thiscode demonstrateshowthe Singletonpatterncan beusedto createacounter to provideunique sequentialnumbers,such asmightbe requiredforuse asprimarykeys ina database: //Sequence.java publicclass Sequence{ privatestatic Sequenceinstance; privatestatic intcounter; privateSequence() counter= 0;//May benecessaryto obtain //starting valueelsewhere... publicstatic synchronizedSequencegetInstance() if(instance==null)// Lazyinstantiation instance= newSequence(); returninstance; publicstatic synchronizedintgetNext() return++counter;
Somethings tonoteabout thisimplementation:
*Synchronizedmethodsare usedtoensure thattheclass isthread-safe. *This classcannotbe subclassedbecausethe constructorisprivate.This mayormay notbe agoodthing dependingonthe resourcebeingprotected. Toallowsubclassing, thevisibility oftheconstructor shouldbechanged toprotected. Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 10of22
*Object serializationcancause problems;ifa Singletonisserialized andthen deserializedmore thanonce,there willbemultiple objectsandnot asingleton.
TheFactory Methodpattern
Inaddition totheSingleton pattern,anothercommon exampleofa creationalpatternis the FactoryMethod. Thispatternis usedwhenit mustbedecided atruntime whichoneof severalcompatible classesisto beinstantiated.This patternisused throughouttheJava API.For example,theabstract Collatorclass'sgetInstance()methodreturns a collationobject thatisappropriate forthedefault locale,asdetermined by java.util.Locale.getDefault():
CollatordefaultCollator =getInstance();
Theconcrete classthatis returnedisactually alwaysasubclass ofCollator, RuleBasedCollator,but thatisan unimportantimplementationdetail. Theinterface definedby theabstractCollatorclassis allthatis requiredtouse it. Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 11of22
Section5. Structuralpatterns
Overview
Structuralpatterns prescribethe organizationofclasses andobjects.These patternsare concernedwith howclassesinherit fromeachother orhowthey arecomposedfrom other classes. Commonstructural patternsincludeAdapter, Proxy,andDecorator patterns.Thesepatterns aresimilar inthatthey introducealevel ofindirectionbetween aclientclass andaclass it wantsto use.Theirintents aredifferent,however. Adapterusesindirection tomodifythe interfaceof aclassto makeiteasier foraclient classtouse it.Decoratoruses indirectionto addbehavior toaclass, withoutundulyaffecting theclientclass. Proxyusesindirection to transparentlyprovide astand-infor anotherclass.
TheAdapter pattern
TheAdapter patternistypically usedtoallow thereuseof aclassthat issimilar,but notthe same,as theclassthe clientclasswould liketosee. Typicallytheoriginal classiscapable of supportingthe behaviortheclient classneeds,but doesnothave theinterfacethe client classexpects, anditis notpossibleor practicaltoalter theoriginalclass. Perhapsthesource codeis notavailable,or itisused elsewhereandchanging theinterfaceis inappropriate. Hereis anexamplethat wrapsOldClasssoa clientclasscan callitusing amethod,
NewMethod()definedin NewInterface:
publicclass OldClassAdapterimplementsNewInterface { privateOldClass ref; publicOldClassAdapter(OldClass oc) ref= oc; publicvoid NewMethod() ref.OldMethod(); Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 12of22
TheProxy andDecoratorpatterns
AProxy isadirect stand-inforanother class,andit typicallyhasthe sameinterfaceas that classbecause itimplementsa commoninterfaceor anabstractclass. Theclientobject isnot awarethat itisusing aproxy.A Proxyisused whenaccessto theclassthe clientwouldlike touse mustbemediated inaway thatisapparent totheclient --becauseit requires restrictedaccess orisa remoteprocess,for example. Decorator,like Proxy,isalso astand-infor anotherclass,and italsohas thesameinterface asthat class,usuallybecause itisa subclass.Theintent isdifferent,however. Thepurpose ofthe Decoratorpatternis toextendthe functionalityofthe originalclassin awaythat is transparentto theclientclass. Examplesof theDecoratorpattern intheJava APIarefound intheclasses forprocessing inputand outputstreams.BufferedReader(),for example,makesreading textfroma file convenientand efficient: BufferedReaderin =newBufferedReader(new FileReader("file.txt"));
TheComposite pattern
TheComposite patternprescribesrecursive compositionforcomplex objects.Theintent isto allowall componentobjectsto betreatedin aconsistentmanner. Allobjects,simple and complex,that participateinthis patternderivefrom acommonabstract componentclassthat definescommon behavior. Forcingrelationships intoapart-whole hierarchyinthis wayminimizesthe typesofobjects thatour system(orclient subsystem)needsto manage.Aclient ofapaint program,for example,could askaline todrawitself inthesame wayitwould askanyother object, includinga compositeobject. Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 13of22
Presentedby developerWorks,yoursource forgreattutorials ibm.com/developerWorks
Javadesign patterns101Page 14of22
Section6. Behavioralpatterns
Overview
Behavioralpatterns prescribethe wayobjectsinteract witheachother. Theyhelpmake complexbehavior manageablebyspecifying theresponsibilitiesof objectsandthe waysthey communicatewith eachother.
TheObserver pattern
Observeris averycommon pattern.Youtypically usethispattern whenyou'reimplementing anapplication withaModel/View/Controller architecture.TheModel/View partofthis design isintended todecouplethe presentationofdata fromthedata itself. Consider,for example,acase wheredatais keptina databaseandcan bedisplayedin multipleformats, asatable oragraph. TheObserverpattern suggeststhatthe display classesregister themselveswiththe classresponsiblefor maintainingthedata, sotheycan benotified whenthedata changes,andso theycanupdate theirdisplays. TheJava APIusesthis patterninthe eventmodelof itsAWT/Swingclasses. Italsoprovides directsupport sothispattern canbeimplemented forotherpurposes. TheJava APIprovidesan Observableclassthat canbesubclassed byobjectsthat wantto beobserved. Amongthemethods Observableprovidesare: *addObserver(Observero) iscalled byObservableobjectsto register themselves. *setChanged()marksthe Observableobjectas havingchanged. *hasChanged()testsif theObservableobjecthas changed. *notifyObservers()notifiesall observersifthe Observableobjecthas changed, accordingto hasChanged(). Togo alongwiththis, anObserverinterfaceis provided,containinga singlemethodthat is calledby anObservableobjectwhen itchanges(providing theObserverhasregisteredquotesdbs_dbs14.pdfusesText_20