SlideShare uma empresa Scribd logo
1 de 27
Conceptos básicos



                     Patrones


           © Copyright 2011. All rights reserved. Ernesto del Puerto.   1
Patrones de diseño y de
    arquitectura

      Un arquitecto planifica los sistemas utilizando un proceso de
       razonamiento basado en patrones.
      Un arquitecto debe estar familiarizado con una variedad de
       catálogos de patrones para ser efectivo.
      Tipos de patrones:
               Los patrones de diseño definen la estructura y el
               comportamiento de componentes OO de software reutilizables
               que permitan realizar los requerimientos funcionales.
               Los patrones de arquitectura definen la estructura y el
               comportamiento del sistema y de los subsistemas para
               cumplimentar los requerimientos no funcionales



© Copyright 2011. All rights reserved. Ernesto del Puerto   2
Patrones de diseño

      A software pattern is a “description of communicating objects
       and classes that are customized to solve a general design
       problem in a particular context.” (Gamma, Helm, Johnson, and
       Vlissides page 3)
      Está inspirado en los patrones de la arquitectura tradicional
       (construcción de edificios)
      Los elementos esenciales de un patrón son:
               Nombre
               Problema
               Solución
               Consecuencias


© Copyright 2011. All rights reserved. Ernesto del Puerto   3
Nivel de los patrones de software

      Patrones de arquitectura:
               Ponen en manifiesto las estructuras de alto nivel de software y
               hardware
               Usualmente soportan los NFRs
      Patrones de diseño:
               Ponen en manifiesto las estructuras de nivel medio de software
               Usualmente soportan los FRs
      Idioms:
               Ponen en manifiesto las estructuras de bajo nivel de software
               (clases y metodos)
               Usualmente soportan funcionalidades específicas del lenguaje



© Copyright 2011. All rights reserved. Ernesto del Puerto   4
Los GoFs




© Copyright 2011. All rights reserved. Ernesto del Puerto   5
Patrones JEE




© Copyright 2011. All rights reserved. Ernesto del Puerto   6
Principio en los patrones

      Existen varios principios para los patrones:
               Open Closed Principle (OCP)
               Composite Reuse Principle (CRP)
               Dependency Inversion Principle (DIP)
      Veamos el siguiente ejemplo:




© Copyright 2011. All rights reserved. Ernesto del Puerto   7
OCP – Open Close Principle

      “Classes should be open for extension but closed for
       modification.” (Knoernschild page 8)




© Copyright 2011. All rights reserved. Ernesto del Puerto   8
CRP – Composite Reuse Principle …

      “Favor polymorphic composition of objects over inheritance.”
       (Knoernschild página 17)




© Copyright 2011. All rights reserved. Ernesto del Puerto   9
… CRP – Composite Reuse Principle

      CRP leads to flexible reuse through delegation




© Copyright 2011. All rights reserved. Ernesto del Puerto   10
DIP – Dependency Inversion Principle …

 “Depend on abstractions. Do not depend on concretions.” (Knoernschild
  page 12)
 Una abstracción puede ser una clase abstracta




© Copyright 2011. All rights reserved. Ernesto del Puerto   11
… DIP – Dependency Inversion Principle

      Una abstracción puede ser una interface




© Copyright 2011. All rights reserved. Ernesto del Puerto   12
Patrón Composite, descripción …

      “Compose objects into tree structures to represent part-whole hierarchies.
       Composite lets clients treat individual objects and compositions of objects
       uniformly.” (GoF page 163)




© Copyright 2011. All rights reserved. Ernesto del Puerto   13
… Patrón Composite, descripción …

      Problem (caracteristicas del problema):
               You want to represent whole-part hierarchies of objects
               You want to use the same interface on the assemblies and the
               components in an assembly
      Solution (caracteristicas de la solucion) :
               Create an abstract class, Component, that acts as the
               superclass for concrete “leaf” and Composite classes.
               The Composite class can be treated as a component because it
               supports the Component class interface.




© Copyright 2011. All rights reserved. Ernesto del Puerto   14
… Patrón Composite, descripción …

El modelo del patrón Composite de GoF




© Copyright 2011. All rights reserved. Ernesto del Puerto   15
… Patrón Composite, descripción …

Modelo alternativo del patrón Composite de GoF




© Copyright 2011. All rights reserved. Ernesto del Puerto   16
… Patrón Composite, descripción …

      Participantes:
               Component (Gráfico):
                        Declares the interface for objects in the composition
                        Implements default behavior for the interface common to all
                        classes, as appropriate
                        Declares an interface for accessing and managing its child
                        components
               Leaf (Rectángulo, Línea, Texto, etc):
                        Represents leaf of objects in the composition. A leaf has no children
                        Defines behavior for primitive objects in the composition




© Copyright 2011. All rights reserved. Ernesto del Puerto   17
… Patrón Composite, descripción …

               Composite (Dibujo):
                        Defines behavior for components having children
                        Stores child components
                        Implements child-related operations in the Component
                        interface
               Client:
                        Manipulates objects in the composition through the
                        Component interface




© Copyright 2011. All rights reserved. Ernesto del Puerto   18
… Patrón Composite, descripción

      Consequences:
               Makes the client simple
               Makes it easier to add new kinds of components
               Can make the design model too general




© Copyright 2011. All rights reserved. Ernesto del Puerto   19
Patrón Strategy, descripción

      “Define a family of algorithms, encapsulate each one, and
       make them interchangeable. Strategy lets the algorithm vary
       independently from clients that use it.” (GoF page 315)




© Copyright 2011. All rights reserved. Ernesto del Puerto   20
Introducing Creational Patterns

          Creational patterns hide the details of object creation.
          Pattern Primary Function
                    Factory Method Creates objects of a class or its
                    subclasses through a method call
                    Abstract Factory Creates a family of objects through
                    a single interface
                    Singleton Restricts a class to one globally accessible
                    instance




© Copyright 2011. All rights reserved. Ernesto del Puerto   21
Applying the Singleton Pattern

     Example Problem
         The hotel system uses a pool of threads to invoke
         processing
         There should only be one instance of the thread pool so that
         all parts of the application are borrowing threads from the
         same pool
         The thread pool must be easily accessible throughout the
         application
     Problem Forces

         There are some classes that are intended to only have a
         single instance
         The single instance of a class may need to be easily
         accessible to different parts of the application
         The only way to secure a constructor is to hide it


© Copyright 2011. All rights reserved. Ernesto del Puerto   22
Singleton Pattern Structure

   Three steps are needed to create a Singleton class:
             1. The Singleton class’ constructor is private or protected,
             hiding it from client view
             2. The Singleton class has a private static reference to the
             only instance of itself
             3. The Singleton class has a public static method that
             returns the single instance




© Copyright 2011. All rights reserved. Ernesto del Puerto   23
Singleton structure code

    public class Singleton {
           private static Singleton uniqueInstance;
           public static Singleton getInstance( ) {
                        if (uniqueInstance == null) {
                                            uniqueInstance = new Singleton();
                        }
                        return uniqueInstance;
           }
           private Singleton( ) {
           }
           //Add attributes and methods for class functionality
    }

© Copyright 2011. All rights reserved. Ernesto del Puerto      24
Singleton Pattern Example Solution




© Copyright 2011. All rights reserved. Ernesto del Puerto   25
Applying the Singleton Pattern

          Consequences
                    Advantages:
                             A client can easily obtain a reference to the single object
                             A singleton can construct the instance at the class
                             loading time or on-demand
                             Singleton can guard several instances at once, not just
                             one
                    Disadvantages:
                             Singleton can replace global variables, but this hint is
                             often misapplied
                             Singleton must make on-demand instances thread-safe




© Copyright 2011. All rights reserved. Ernesto del Puerto   26
Bibliografía

         Design Petterns. Elements of Reusable Object-Oriented
          Software. E. Gamma, R. Helm, R. Johnson y J. Vlissides.
          Addison-Wesley. 32nd. Printing. April 2005. ISBN:
          0201663612.
         SL-500. J2EE Patterns. Student Guide. Sun Education.
          Revision C. 2003.
         Patterns of Enterprise Application Architecture. Martin
          Fowler. Addison-Wesley. Thirteenth Printing. October
          2007. ISBN: 0-321-12742-0.
         Head First Design Patterns. Eric y Elisabeth Freeman.
          O’Reilly. First Edition. October 2004. ISBN: 0-596-00712-
          4.



© Copyright 2011. All rights reserved. Ernesto del Puerto   27

Mais conteúdo relacionado

Semelhante a 01 J2EE patrones

Prophecy Of Design Patterns
Prophecy Of Design PatternsProphecy Of Design Patterns
Prophecy Of Design Patternspradeepkothiyal
 
Design Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur UniversityDesign Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur UniversityShubham Narkhede
 
Design pattern in Symfony2 - Nanos gigantium humeris insidentes
Design pattern in Symfony2 - Nanos gigantium humeris insidentesDesign pattern in Symfony2 - Nanos gigantium humeris insidentes
Design pattern in Symfony2 - Nanos gigantium humeris insidentesGiulio De Donato
 
Make Me an Eclipse View (with less Plumbing): The PTP External Tools Framewor...
Make Me an Eclipse View (with less Plumbing): The PTP External Tools Framewor...Make Me an Eclipse View (with less Plumbing): The PTP External Tools Framewor...
Make Me an Eclipse View (with less Plumbing): The PTP External Tools Framewor...bethtib
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternNishith Shukla
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 
Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of PatternsChris Eargle
 
Using design pattern for mobile
Using design pattern for mobileUsing design pattern for mobile
Using design pattern for mobileluca mezzalira
 
Designing a Development Environment for Logic and Multi-Paradigm Programming
Designing a Development Environment for Logic and Multi-Paradigm ProgrammingDesigning a Development Environment for Logic and Multi-Paradigm Programming
Designing a Development Environment for Logic and Multi-Paradigm Programminggpiancastelli
 
NeOn Tool Support for Building Ontologies By Reuse - ICBO 09
NeOn Tool Support for Building Ontologies By Reuse - ICBO 09NeOn Tool Support for Building Ontologies By Reuse - ICBO 09
NeOn Tool Support for Building Ontologies By Reuse - ICBO 09Mathieu d'Aquin
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSeerat Malik
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonJonathan Simon
 
Singleton Object Management
Singleton Object ManagementSingleton Object Management
Singleton Object Managementppd1961
 

Semelhante a 01 J2EE patrones (20)

Clarity in Documentation
Clarity in DocumentationClarity in Documentation
Clarity in Documentation
 
Prophecy Of Design Patterns
Prophecy Of Design PatternsProphecy Of Design Patterns
Prophecy Of Design Patterns
 
Design Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur UniversityDesign Pattern Notes: Nagpur University
Design Pattern Notes: Nagpur University
 
Testing method pptx
Testing method pptxTesting method pptx
Testing method pptx
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
Design pattern in Symfony2 - Nanos gigantium humeris insidentes
Design pattern in Symfony2 - Nanos gigantium humeris insidentesDesign pattern in Symfony2 - Nanos gigantium humeris insidentes
Design pattern in Symfony2 - Nanos gigantium humeris insidentes
 
Make Me an Eclipse View (with less Plumbing): The PTP External Tools Framewor...
Make Me an Eclipse View (with less Plumbing): The PTP External Tools Framewor...Make Me an Eclipse View (with less Plumbing): The PTP External Tools Framewor...
Make Me an Eclipse View (with less Plumbing): The PTP External Tools Framewor...
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Evolution of Patterns
Evolution of PatternsEvolution of Patterns
Evolution of Patterns
 
Using design pattern for mobile
Using design pattern for mobileUsing design pattern for mobile
Using design pattern for mobile
 
Designing a Development Environment for Logic and Multi-Paradigm Programming
Designing a Development Environment for Logic and Multi-Paradigm ProgrammingDesigning a Development Environment for Logic and Multi-Paradigm Programming
Designing a Development Environment for Logic and Multi-Paradigm Programming
 
NeOn Tool Support for Building Ontologies By Reuse - ICBO 09
NeOn Tool Support for Building Ontologies By Reuse - ICBO 09NeOn Tool Support for Building Ontologies By Reuse - ICBO 09
NeOn Tool Support for Building Ontologies By Reuse - ICBO 09
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation Pattern
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Lecture11
Lecture11Lecture11
Lecture11
 
Singleton Object Management
Singleton Object ManagementSingleton Object Management
Singleton Object Management
 
Onion (clean) architecture
Onion (clean) architectureOnion (clean) architecture
Onion (clean) architecture
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 

Último

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Último (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

01 J2EE patrones

  • 1. Conceptos básicos Patrones © Copyright 2011. All rights reserved. Ernesto del Puerto. 1
  • 2. Patrones de diseño y de arquitectura  Un arquitecto planifica los sistemas utilizando un proceso de razonamiento basado en patrones.  Un arquitecto debe estar familiarizado con una variedad de catálogos de patrones para ser efectivo.  Tipos de patrones: Los patrones de diseño definen la estructura y el comportamiento de componentes OO de software reutilizables que permitan realizar los requerimientos funcionales. Los patrones de arquitectura definen la estructura y el comportamiento del sistema y de los subsistemas para cumplimentar los requerimientos no funcionales © Copyright 2011. All rights reserved. Ernesto del Puerto 2
  • 3. Patrones de diseño  A software pattern is a “description of communicating objects and classes that are customized to solve a general design problem in a particular context.” (Gamma, Helm, Johnson, and Vlissides page 3)  Está inspirado en los patrones de la arquitectura tradicional (construcción de edificios)  Los elementos esenciales de un patrón son: Nombre Problema Solución Consecuencias © Copyright 2011. All rights reserved. Ernesto del Puerto 3
  • 4. Nivel de los patrones de software  Patrones de arquitectura: Ponen en manifiesto las estructuras de alto nivel de software y hardware Usualmente soportan los NFRs  Patrones de diseño: Ponen en manifiesto las estructuras de nivel medio de software Usualmente soportan los FRs  Idioms: Ponen en manifiesto las estructuras de bajo nivel de software (clases y metodos) Usualmente soportan funcionalidades específicas del lenguaje © Copyright 2011. All rights reserved. Ernesto del Puerto 4
  • 5. Los GoFs © Copyright 2011. All rights reserved. Ernesto del Puerto 5
  • 6. Patrones JEE © Copyright 2011. All rights reserved. Ernesto del Puerto 6
  • 7. Principio en los patrones  Existen varios principios para los patrones: Open Closed Principle (OCP) Composite Reuse Principle (CRP) Dependency Inversion Principle (DIP)  Veamos el siguiente ejemplo: © Copyright 2011. All rights reserved. Ernesto del Puerto 7
  • 8. OCP – Open Close Principle  “Classes should be open for extension but closed for modification.” (Knoernschild page 8) © Copyright 2011. All rights reserved. Ernesto del Puerto 8
  • 9. CRP – Composite Reuse Principle …  “Favor polymorphic composition of objects over inheritance.” (Knoernschild página 17) © Copyright 2011. All rights reserved. Ernesto del Puerto 9
  • 10. … CRP – Composite Reuse Principle  CRP leads to flexible reuse through delegation © Copyright 2011. All rights reserved. Ernesto del Puerto 10
  • 11. DIP – Dependency Inversion Principle …  “Depend on abstractions. Do not depend on concretions.” (Knoernschild page 12)  Una abstracción puede ser una clase abstracta © Copyright 2011. All rights reserved. Ernesto del Puerto 11
  • 12. … DIP – Dependency Inversion Principle  Una abstracción puede ser una interface © Copyright 2011. All rights reserved. Ernesto del Puerto 12
  • 13. Patrón Composite, descripción …  “Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.” (GoF page 163) © Copyright 2011. All rights reserved. Ernesto del Puerto 13
  • 14. … Patrón Composite, descripción …  Problem (caracteristicas del problema): You want to represent whole-part hierarchies of objects You want to use the same interface on the assemblies and the components in an assembly  Solution (caracteristicas de la solucion) : Create an abstract class, Component, that acts as the superclass for concrete “leaf” and Composite classes. The Composite class can be treated as a component because it supports the Component class interface. © Copyright 2011. All rights reserved. Ernesto del Puerto 14
  • 15. … Patrón Composite, descripción … El modelo del patrón Composite de GoF © Copyright 2011. All rights reserved. Ernesto del Puerto 15
  • 16. … Patrón Composite, descripción … Modelo alternativo del patrón Composite de GoF © Copyright 2011. All rights reserved. Ernesto del Puerto 16
  • 17. … Patrón Composite, descripción …  Participantes: Component (Gráfico): Declares the interface for objects in the composition Implements default behavior for the interface common to all classes, as appropriate Declares an interface for accessing and managing its child components Leaf (Rectángulo, Línea, Texto, etc): Represents leaf of objects in the composition. A leaf has no children Defines behavior for primitive objects in the composition © Copyright 2011. All rights reserved. Ernesto del Puerto 17
  • 18. … Patrón Composite, descripción … Composite (Dibujo): Defines behavior for components having children Stores child components Implements child-related operations in the Component interface Client: Manipulates objects in the composition through the Component interface © Copyright 2011. All rights reserved. Ernesto del Puerto 18
  • 19. … Patrón Composite, descripción  Consequences: Makes the client simple Makes it easier to add new kinds of components Can make the design model too general © Copyright 2011. All rights reserved. Ernesto del Puerto 19
  • 20. Patrón Strategy, descripción  “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.” (GoF page 315) © Copyright 2011. All rights reserved. Ernesto del Puerto 20
  • 21. Introducing Creational Patterns  Creational patterns hide the details of object creation.  Pattern Primary Function Factory Method Creates objects of a class or its subclasses through a method call Abstract Factory Creates a family of objects through a single interface Singleton Restricts a class to one globally accessible instance © Copyright 2011. All rights reserved. Ernesto del Puerto 21
  • 22. Applying the Singleton Pattern  Example Problem The hotel system uses a pool of threads to invoke processing There should only be one instance of the thread pool so that all parts of the application are borrowing threads from the same pool The thread pool must be easily accessible throughout the application  Problem Forces There are some classes that are intended to only have a single instance The single instance of a class may need to be easily accessible to different parts of the application The only way to secure a constructor is to hide it © Copyright 2011. All rights reserved. Ernesto del Puerto 22
  • 23. Singleton Pattern Structure  Three steps are needed to create a Singleton class: 1. The Singleton class’ constructor is private or protected, hiding it from client view 2. The Singleton class has a private static reference to the only instance of itself 3. The Singleton class has a public static method that returns the single instance © Copyright 2011. All rights reserved. Ernesto del Puerto 23
  • 24. Singleton structure code public class Singleton { private static Singleton uniqueInstance; public static Singleton getInstance( ) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } private Singleton( ) { } //Add attributes and methods for class functionality } © Copyright 2011. All rights reserved. Ernesto del Puerto 24
  • 25. Singleton Pattern Example Solution © Copyright 2011. All rights reserved. Ernesto del Puerto 25
  • 26. Applying the Singleton Pattern  Consequences Advantages: A client can easily obtain a reference to the single object A singleton can construct the instance at the class loading time or on-demand Singleton can guard several instances at once, not just one Disadvantages: Singleton can replace global variables, but this hint is often misapplied Singleton must make on-demand instances thread-safe © Copyright 2011. All rights reserved. Ernesto del Puerto 26
  • 27. Bibliografía  Design Petterns. Elements of Reusable Object-Oriented Software. E. Gamma, R. Helm, R. Johnson y J. Vlissides. Addison-Wesley. 32nd. Printing. April 2005. ISBN: 0201663612.  SL-500. J2EE Patterns. Student Guide. Sun Education. Revision C. 2003.  Patterns of Enterprise Application Architecture. Martin Fowler. Addison-Wesley. Thirteenth Printing. October 2007. ISBN: 0-321-12742-0.  Head First Design Patterns. Eric y Elisabeth Freeman. O’Reilly. First Edition. October 2004. ISBN: 0-596-00712- 4. © Copyright 2011. All rights reserved. Ernesto del Puerto 27

Notas do Editor

  1. Este material fue preparado especialmente para los cursos que organizó la SCEU de la UTN FRBA en el Campus correspondientes al proyecto Becas Control F desde fines de 2010 hasta principios de 2011.