/
Patron: Decorator Patron: Decorator

Patron: Decorator - PDF document

yoshiko-marsland
yoshiko-marsland . @yoshiko-marsland
Follow
384 views
Uploaded On 2016-11-15

Patron: Decorator - PPT Presentation

gibsonTeachingDesignPatternsDesignPatterns Decoratorpdf TSP June2013Patrons De ConceptionJ Paul Gibson Decorator 1 gibsonTeachingDesignPatternsDesignPatterns Decoratorpdf ID: 489102

/~ gibson/Teaching/DesignPatterns/DesignPatterns - Decorator.pdf TSP -June2013Patrons ConceptionJ Paul

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "Patron: Decorator" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Patron: Decorator /~ gibson/Teaching/DesignPatterns/DesignPatterns - Decorator.pdf TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .1 /~ gibson/Teaching/DesignPatterns/DesignPatterns - Decorator.pdf Patron: Decorator Ajout dynamique de responsabilités à un objet. L'ajout de responsabilités à un objet sonne évidemment comme un héritage. C'est en effet, le moyen le plus évident de lui fournir des responsabilités supplémentaires. Le manque de souplesse de cette méthode (l'héritage) est bien entendu, son inconvénient majeur. TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .2 entendu, son inconvénient majeur. Premièrement, l'héritage n'est pas toujours possible. Deuxièmement, l'héritage peut donner lieu à la prolifération de classes. Enfin, les responsabilités supplémentaires ne sont pas dynamiques. Patron: Decorator L'héritage n'est pas toujours possible/desirable Vous n'avez en effet pas toujours moyen d'accéder à la classe mère, vous ne l'avez pas nécessairement développée vous-même et elle peut être définie comme étant finale. TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .3Il peut aussi arriver que la classe ne soit pas finale mais qu'en hériter vous rende nerveux à l'idée de devoir maintenir dans toutes vos classes héritières toute modification apportée par l'éditeur de cette classe. Patron: Decorator Evite la prolifération de classes :Imaginons que l'on ai définie une classe dont on veut étendre les capacités. Par exemple nous avons la classe Loggeret on veut ajouter à chaque message envoyer vers le logger, l'heure et la date d'émission. Imaginons de plus que nous voulions aussi définir TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .4 d'émission. Imaginons de plus que nous voulions aussi définir une classe pour un affichage console, un log dans un fichier, un log par email à un administrateur un affichage SWING ! Dans chaque cas, il faut pouvoir afficher ou non l'heure et la date. Nous voilà donc obligés de surcharger la classe logger (pour un fichier) 3 fois pour les divers types de logger et 2 fois pour que chacun affiche l'heure et la date, ou non. Patron: Decorator (UML) TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .5 Patron: Decorator (UML) Les responsabilités supplémentaires –avec l’heritage -ne sont pas dynamiquesEt le dynamisme peut se représenter par plusieurs choses aussi utiles qu'esthétiquesUn dynamisme en runtime : à tout moment vous pouvez basculer du mode horodaté au mode sans horodatage, du mode swing au mode console, etc.Enfin, et on découvre alors là une grande puissance du pattern Décorateur, vous pouvez composer les différentes parties entre elles. Un exemple : Logger classique (donc fichier) associé à LoggerHorodaté (donc horodatage des messages) associés à TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .6 (donc fichier) associé à LoggerHorodaté (donc horodatage des messages) associés à LoggerSwing (donc affichage écran graphique) donne des résultats dans un fichier et dans un écran, le tout horodaté. Pour faire cela avec l'héritage pur, il m'aurait fallu hériter par exemple de LoggerSwingHorodaté et ajouter les responsabilités pourtant déjà implémentées de log dans un fichier ! Soit encore une classe. Patron: Decorator (UML pour logger) Generique Decorator TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .7 Patron: Decorator TP –Christmas Tree  \n \n\r       \r\r \n \n\r  \n \n   \r Download source code from : TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .8 Download source code from : Decorator.zip Patron: Decorator TP –Christmas Tree TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .9 Patron: Decorator TP –Christmas Tree package specifications; publicinterface BranchOfTreeSpecification{ TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .10 publicvoid animate(); public String getDecorations(); Patron: Decorator TP –Christmas Tree package specifications; publicabstractclass BranchDecoratorSpecifiation implements BranchOfTreeSpecification{ protected BranchOfTreeSpecification decoratedBranch ; public BranchDecoratorSpecifiation(BranchOfTreeSpecificationbranchToDecorate){ decoratedBranch = branchToDecorate; } TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .11 } publicvoid animate(){ decoratedBranch .animate(); } Patron: Decorator TP –Christmas Tree package models; import specifications.BranchOfTreeSpecification; publicclass UndecoratedBranch implements BranchOfTreeSpecification{ publicvoid animate(){} TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .12 public String getDecorations(){ return "" ;} Patron: Decorator TP –Christmas Tree package models; import specifications.BranchDecoratorSpecifiation; import specifications.BranchOfTreeSpecification; publicclass BallDecorator extends BranchDecoratorSpecifiation{ boolean spinning ; public BallDecorator(BranchOfTreeSpecificationbranchOfTree){ super (branchOfTree); spinning = true ;} public String getDecorations(){ String str = decoratedBranch .getDecorations (); TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .13 String str = decoratedBranch .getDecorations (); if ( spinning ) str= str+ " Spinning" str= str+ " Ball." ; return str; publicvoid animate(){ decoratedBranch .animate (); spinning = ! spinning } Patron: Decorator TP –Christmas Tree package models; import specifications.BranchDecoratorSpecifiation; import specifications.BranchOfTreeSpecification; publicclass LightsDecorator extends BranchDecoratorSpecifiation{String colour ; public LightsDecorator(BranchOfTreeSpecificationbranchOfTree){ super (branchOfTree); colour = "red" ;} public String getDecorations(){ String str = decoratedBranch .getDecorations (); TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .14 String str = decoratedBranch .getDecorations (); str=str+ " colour= " + colour ; return str; publicvoid animate(){ decoratedBranch .animate(); if ( colour .equals( "red" )) colour = "white" ; elseif ( colour .equals( "white" )) colour = "blue" ; else colour = "red" } Patron: Decorator TP –Christmas Tree publicclass TestBallDecorator{ publicstaticvoid main (String [] args){BranchOfTreeSpecificationplainBranch= new UndecoratedBranch();BranchOfTreeSpecificationdecoratedBranch= new BallDecorator( plainBranch);BranchOfTreeSpecificationreDecoratedBranch= new BallDecorator( new BallDecorator( plainBranch));System. out .println( "plainBranch.getDecorations() =" +plainBranch.getDecorations());System. out .println( "decoratedBranch.getDecorations() =" +decoratedBranch.getDecorations());System. out .println( "reDecoratedBranch.getDecorations() =" +reDecoratedBranch.getDecorations()); plainBranch.animate (); TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .15 plainBranch.animate (); System. out .println( "plainBranch.animate.getDecorations() =" +plainBranch.getDecorations());decoratedBranch.animate();System. out .println( "decoratedBranch.animate.getDecorations() =" +decoratedBranch.getDecorations());reDecoratedBranch.animate();System. out .println( "reDecoratedBranch.animate.getDecorations() =" +reDecoratedBranch.getDecorations()); Patron: Decorator TP –Christmas Tree TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .16 Patron: Decorator TP –Christmas TreeTO DO: •Test Lights Decoration•Test Lights withBalls•Adddecoration(Stars, eg)•Test 3 decorationstogetherCreateXMAS treewith4 branches:•2 Lights and 2 Balls • 2 Lights and 3 Stars TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .17 • 2 Lights and 3 Stars •2 Stars and 3 Balls•2 Lights and 2 Stars and 2 BallsEnsurethatthe state of decorationson the samebranchof treeisco-ordinated(but not necessarilyon differentbranches) Patron: Decorator TP –Christmas Tree Whatto learnfromthe problemIf youreallyneedmultiple instances of samedecorationthenthispattern isprobablynot correct. TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .18 NOTE: As requirementschange youmaybetemptedto compromise yoursystem by holding on to a pattern whichisno longer appropriate Patron: Decorator TP –Christmas Tree Solvingthe problemIf wereallyneedmultiple decorationsof the sametype on a single branchdo not use the decoratorpattern in thiswayWeshouldfixthe decoratorpattern sothatdecoratinga branchwithballbehaviourthathas alreadybeen decoratedwithballbehaviouriseither: • Handled by an exception, or TSP -June2013Patrons De ConceptionJ Paul Gibson Decorator .19 • Handled by an exception, or •IgnoredTO DO –implementone of thesesolutions, and retestthe new behaviour