Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

OOD Principles and Patterns

1 485 vues

Publié le

OOD Principles and Patterns

Publié dans : Technologie

OOD Principles and Patterns

  1. 1. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 1 Training objectives Duration: 3 hours Purpose: In the course, student will learn to:  Understanding the design principles.  Understanding the design patterns.  How to apply basic patterns. Attendees : DEVs & Designers Test: N/A
  2. 2. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 2 OOD Principles and Patterns Instructor: Tung.Nguyen Author: tungnq@fsoft.com.vn
  3. 3. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 3 Training Agenda •Introduce •Design Principles •Design Patterns •Q&A
  4. 4. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 4 How Do You Design? What principles guide you when you create a design? What considerations are important? When have you done enough design and can begin implementation? Take a piece of paper and write down two principles that guide you - considerations that are important or indicators that you have a good design.
  5. 5. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 5 Design Level Architectures/Framework (Financial System, J2EE,…) OOD Patterns OOD Principles Specific Data Structures Algorithmic Approaches General + OO Concepts
  6. 6. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 6 Major Topics in Design Principles of Object-Oriented Design Principles of Package Architecture Basic Patterns Catalog of GoF Patterns Other Micro-Architecture Patterns Concurrency Patterns Patterns-Oriented Software Architecture Catalog of J2EE Patterns Enterprise Integration Patterns
  7. 7. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 7 Key Design Concepts General •Cohesion •Coupling •Information hiding •Encapsulation •Creation •Binding time OO Specific •Behaviors follow data •Class vs. Interface Inheritance •Class = implementation •Interface = type •Inheritance / composition / delegation
  8. 8. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 8 UML Notation Overview http://www.uml.org/
  9. 9. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 9 What’s Purpose Of Design? What’s a design?  Express a idea to resolve a problem.  Use for communications in the team members. What’s a good design? “Cohesion and Coupling deal with the quality of an OO design”  Easy for Developing, reading & understanding.  Easy for Communication.  Easy for Extending (add new features)  Easy for Maintenance.  “Loose coupling and high cohesion” idea!!!
  10. 10. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 10 Cohesion and Coupling Coupling Coupling or Dependency is the degree to which each program module relies on each one of the other modules. Cohesion Cohesion refers to the degree to which the elements of a module belong together. Cohesion is a measure of how strongly- related or focused the responsibilities of a single module are. class Coupling «interface» IProductApplicationProduct AProduct BService BService ALoosely coupledwhat's happen when changing Service A --> Service B?
  11. 11. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 11 Symptoms of Rotting Design Rigidity: It is hard to change because every change affects too many other parts of the system. Fragility: Closely related to rigidity is fragility. When you make a change, unexpected parts of the system break. Immobility: It is hard to reuse in another application because it cannot be disentangled from the current application.
  12. 12. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 12 Training Agenda •Introduce •Design Principles •Basic Design Patterns •Q&A
  13. 13. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 13 Principles of OO Class Design 5 Principles of OO Class Design SRP: The Single Responsibility Principle OCP: The Open Closed Principle LSP: The Liskov Substitution Principle ISP: The Interface Segregation Principle DIP: The Dependency Inversion Principle
  14. 14. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 14 Principles of OO Class Design SRP: The Single Responsibility Principle “There should never be more than one reason for a class to change” Or “A class should have one, and only one type of responsibility.”
  15. 15. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 15 Principles of OO Class Design SRP: The Single Responsibility Principle (cont) Sample: Consider the following Rectangle class Two applications are using this Rectangle class: Computational Geometry Application uses this class to calculate the Area Graphical Application uses this class to draw a Rectangle in the UI
  16. 16. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 16 Principles of OO Class Design SRP: The Single Responsibility Principle (cont) This violates SRP design principle as the Rectangle class has two responsibilities:  It calculates the value of the Rectangular area.  It renders the Rectangle in the UI. So, what is the problem?  We must include the GUI in the computational geometry application. While deployment of the geometry application, we must include GUI library. A change to the Rectangle class for Graphical application may lead to change, build and test the Computational geometry application.
  17. 17. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 17 Principles of OO Class Design SRP: The Single Responsibility Principle (cont) A better design is to separate the two responsibilities into two completely different classes Why is it important to separate these two responsibilities into separate classes?
  18. 18. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 18 Principles of OO Class Design SRP: The Single Responsibility Principle (cont) What is a Responsibility? “Responsibility” is defined as “a reason for change”. “Modem” sample  dial & hangup functions for managing connection  send & recv functions for data communication  Should separate into 2 repositories!
  19. 19. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 19 Principles of OO Class Design OCP: The Open Closed Principle “Software entities(classes, modules, functions, etc.) should be open for extension, but closed for modification.” - Bertrand Meyer, 1988 Or “You should be able to extend a classes behavior, without modifying code” “Open for extension” This means that the behavior of the module/class can be extended and we can make the module behave in new and different ways as the requirements changes, or to meet the needs of new applications “Closed for Modification” The source code of such a module is inviolate. No one is allowed to make source code changes to it
  20. 20. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 20 Principles of OO Class Design OCP: The Open Closed Principle (cont) Sample: Doesn’t support Open-Close Principle Client & Server classes are concrete. If the Server implementation/class is changed, Client also needs change.  How to resolve this problem?
  21. 21. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 21 Principles of OO Class Design OCP: The Open Closed Principle (cont) Change to support Open-Closed Principle. Abstracion is the key. The Concrete Server class implements the Abstract Server class. The Server implementation is changed, the Client is likely not to require any change. The Abstract Server class here is closed for modification and the Concrete class implementations here are Open for extension.
  22. 22. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 22 Principles of OO Class Design LSP: The Liskov Substitution Principle “Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.” Or “Subclasses should be substitutable for their base classes.”
  23. 23. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 23 Principles of OO Class Design LSP: The Liskov Substitution Principle (cont) the KingFisher class extends the Bird base class and hence, inherits the Fly() method. Ostrich is also a Bird (Definitely it is!) and hence it inherits the Bird class. Now, can it fly? No! Here the design violates the LSP.  So, even if in real world this seems natural, in the class design, Ostrich should not inherit the Bird class and there should be a separate class for birds that can’t really fly and Ostrich should inherit that.
  24. 24. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 24 Principles of OO Class Design LSP: The Liskov Substitution Principle (cont) In basic Object Oriented Principle, “Inheritance” is usually described as an "is a" relationship. Such “Is a” relationship is very important in class designs, but, its easy to get carried away and end up in wrong design with bad inheritance.  The “Liskov Substitution Principle” is a way of ensuring that inheritance is used correctly.
  25. 25. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 25 Principles of OO Class Design LSP: The Liskov Substitution Principle (cont) Why The LSP is so important?  If LSP is not maintained, class hierarchies would be a mess and if subclass instance was passed as parameter to methods method, strange behavior might occur.  If LSP is not maintained, unit tests for the Base classes would never succeed for the subclass. LSP is just an extension of Open-Close Principle!!!
  26. 26. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 26 Principles of OO Class Design ISP: The Interface Segregation Principle “Client should not be forced to depend upon interface that they do not use.” Or “Many client specific interfaces are better than one general purpose interface.”
  27. 27. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 27 Principles of OO Class Design ISP: The Interface Segregation Principle (cont) Sample: Providing service for Client A,B,C {Applying ISP}
  28. 28. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 28 Principles of OO Class Design ISP: The Interface Segregation Principle (cont) Interfaces with too many methods are less re-usable. Such "fat interfaces“ with additional useless methods lead to inadvertent coupling between classes. Doing this also introduce unnecessary complexity and reduces maintainability or robustness in the system. The ISP ensures that, Interfaces are developed so that, each of them have their own responsibility and thus they are re-usable.
  29. 29. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 29 Principles of OO Class Design DIP: The Dependency Inversion Principle “High level modules should not depend upon low level modules. Both should depend upon abstractions” Or “Abstractions should not depend upon details. Details should depend upon abstraction.” Or “Depend upon Abstractions. Do not depend upon concretions.”
  30. 30. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 30 Principles of OO Class Design DIP: The Dependency Inversion Principle (cont) The DIP is the strategy of depending upon interfaces or abstract functions and classes, rather than upon concrete functions and classes. The DIP describes the overall structure of a well designed object-oriented application. Sample: Layers of application
  31. 31. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 31 6 Principles of Package Architecture 3 The Package Cohesion Principles REP: The Release/Reuse Equivalency Principle CRP: The Common Reuse Principle CCP: The Common Closure Principle 3 The Package Coupling Principles ADP: The Acyclic Dependencies Principle SDP: The Stable Dependencies Principle SAP: The Stable Abstractions Principle
  32. 32. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 32 Why? When software application grows in size and complexity  they require some kind of high level organization. Applying for large application.
  33. 33. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 33 Design with Packages Packages can be used as containers for a group of classes:  The design at a high level of abstraction. The relationships between those packages expresses the high level organization of the application Question for package design? What are the best grouping criteria? What are the relationships that exist between packages, and what design principles govern their use? Should packages be designed before classes (Top down)? Or should classes be designed before packages (Bottom up)? How are packages physically represented? Once created, to what purpose will we put these packages?
  34. 34. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 34 The Package Cohesion Principles REP: The Release/Reuse Equivalency Principle “The granule of reuse is the granule of release. Only components that are released through a tracking system can be effectively reused. This granule is the package.” Or “The granule of reuse is the granule of release. Anything that it is reused must also be released”
  35. 35. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 35 The Package Cohesion Principles REP: The Release/Reuse Equivalency Principle Packages are a candidate for a releasable entity. Packages might be possible to release and track classes (release version).
  36. 36. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 36 The Package Cohesion Principles CRP: The Common Reuse Principle “The classes in a package are reused together. If you reuse one of the classes in a package, you reuse them all.” Or “Classes that are used together are packaged together.” Or “Classes that aren’t reused together should not be grouped together.”
  37. 37. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 37 The Package Cohesion Principles CRP: The Common Reuse Principle A dependency upon a package is a dependency upon everything within the package. Which classes should be placed into a package? Generally reusable classes collaborate with other classes that are part of the reusable abstraction  These classes belong together in the same package.
  38. 38. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 38 The Package Cohesion Principles CCP: The Common Closure Principle “The classes in a package should be closed together against the same kinds of changes. A change that affects a package affects all the classes in that package.” Or “Classes that change together are packaged together.”
  39. 39. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 39 The Package Cohesion Principles CCP: The Common Closure Principle More important than reusability, is maintainability. What’s happen when application must change code?  changing at: all in one package, or distributed through many packages? All classes having the same changing reason must belong in the same package  This minimizes the workload related to releasing, revalidating, and redistributing the software.
  40. 40. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 40 The Package Cohesion Principles Review The REP and CRP makes life easy for reuse. The CCP makes life easier for maintenance. The CCP strives to make packages as large as possible. The CRP tries to make packages very small.
  41. 41. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 41 6 Principles of Package Architecture 3 The Package Cohesion Principles REP: The Release/Reuse Equivalency Principle CRP: The Common Reuse Principle CCP: The Common Closure Principle 3 The Package Coupling Principles ADP: The Acyclic Dependencies Principle SDP: The Stable Dependencies Principle SAP: The Stable Abstractions Principle
  42. 42. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 42 The Package Cohesion Principles ADP: The Acyclic Dependencies Principle “The dependency structure between packages must be a directed acyclic graph (DAG). That is, there must be no cycles in the dependency structure.” Or “The dependencies between packages must not form cycles.”
  43. 43. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 43 The Package Cohesion Principles ADP: The Acyclic Dependencies Principle Sample: Acyclic Package Network  What happen when releasing Protocol package? •Build with latest CommError package. •Run & Test Protocol package. Test & Release with minimal amount of work.
  44. 44. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 44 The Package Cohesion Principles ADP: The Acyclic Dependencies Principle Sample: A Cycle Creeps In CommError can display error msg on GUI. What happen when Protocol package?  Build & Test everything!!!
  45. 45. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 45 The Package Cohesion Principles ADP: The Acyclic Dependencies Principle Sample: Breaking Cycle There are 2 ways to break cycle: -Creating new package. -Make use of DIP and ISP. Both GUI & CommError packages depend upon one new package Message Manager
  46. 46. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 46 The Package Cohesion Principles ADP: The Acyclic Dependencies Principle Sample: Breaking Cycle Using “BY” interface. There are 2 ways to break cycle: -Creating new package. -Make use of DIP and ISP.
  47. 47. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 47 The Package Cohesion Principles SDP: The Stable Dependencies Principle “The dependencies between packages in a design should be the direction of the stability of the packages. A package should only depend upon packages that are more stable that it is” Or “Depend in the direction of stability.”
  48. 48. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 48 The Package Cohesion Principles SDP: The Stable Dependencies Principle Stability is a measure of the difficulty in changing a module. The package is difficult to change because a lot of other packages depend upon it. A package with a lot of incoming dependencies is very stable because it requires a great deal of work to reconcile any changes with all the dependent packages. The package is more Stable  it is less Flexible.
  49. 49. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 49 The Package Cohesion Principles SDP: The Stable Dependencies Principle Package X has 3 packages depending upon it.  X has 3 good reasons not to change!  X is responsible to those 3 packages. Package Y has no other packages depending upon it  Y is irresponsible. X is a stable package Y is a instable package
  50. 50. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 50 The Package Cohesion Principles SDP: The Stable Dependencies Principle Stability Matrix: is used to calculate the possible stability of the package.  Ca : Afferent Couplings : The number of classes outside this package that depend upon classes within this package.  Ce : Efferent Couplings : The number of classes inside this package that depend upon classes outside this package.  I : Instability : (Ce ÷(Ca+Ce)) : This metric has the range [0,1] •I=0 indicates a maximally stable package. •I=1 indicates a maximally instable package.
  51. 51. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 51 The Package Cohesion Principles SDP: The Stable Dependencies Principle Sample: Ca=4, Ce=3, and I=3/7
  52. 52. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 52 The Package Cohesion Principles SDP: The Stable Dependencies Principle The I metric of a package should be larger than the I metrics of the packages that it depends upon. The I metrics should decrease in the direction of dependency. All the packages in a system were maximally stable (I=0), the system would be unchangeable.
  53. 53. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 53 The Package Cohesion Principles SAP: The Stable Abstractions Principle “Packages that are maximally stable should be maximally abstract. Instable packages should be concrete. The abstraction of a package should be in proportion to its stability.” Or “Stable packages should be abstract packages.” Or “Abstractness increases with stability.”
  54. 54. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 54 The Package Cohesion Principles SAP: The Stable Abstractions Principle A package is to be stable, it should also consist of abstract classes so that it can be extended. Stable packages that are extensible are flexible and do not constrain the design. The Abstractness Metrics:  Nc: Number of classes in package.  Na: Number of abstract classes in package.  A: Abstractness [0,1]. A= Na/Nc
  55. 55. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 55 Sample: Package Diagram pkg Logical Architecture OverviewClient LayerPresentation LayerBusiness Logic LayerData Access LayerDatabase & External System LayerCommons LayerStruts 2.x(from Frameworks) webRichFace(from Frameworks) JSP(from Frameworks) SpringSecurity 3.x(from Frameworks) businesshibernate(from dao) email(from dao) ldap(from dao) Architecture Overview:: SMTP ServerArchitecture Overview:: Database schema Oracle 11gArchitecture Overview:: Group Directory SystemSpring Transation Manager 3.x(from Frameworks) Hibernate JPA 3.6.x(from Frameworks) schedulerSpringBatch 2.x(from Frameworks) Users(from Use Case View) modelSpring IoC 3.x(from Frameworks) utils«use» «forward» «use» «use» «use» «use» «access» «use» JDBC «access» LDAP «access» «use» «use» https«use» «dependency injection» SMTP/IMAP «access»
  56. 56. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 56 Training Agenda •Introduce •Design Principles •Basic Design Patterns •Q&A
  57. 57. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 57 What are Patterns? "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice." - Christopher Alexander A pattern is a general solution to a problem in a context • general -- outline of approach only • problem -- a recurring issue • context -- consider the expected design evolution
  58. 58. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 58 What are Patterns About? Standard patterns of interactions between classes Design patterns How to apply them to your application Deal with subsystems at the higher level of abstraction provided by the patterns What to do when it does not fit exactly Evaluate options and analyze the trade-offs
  59. 59. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 59 Why Patterns? Design for re-use is difficult Experienced designers: Rarely start from first principles Apply a working "handbook" of approaches Patterns make this ephemeral knowledge available to all. Support evaluation of alternatives at higher level of abstraction.
  60. 60. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 60 Benefit from Design Pattern Design Patterns give you a shared vocabulary with other developers. Shared pattern vocabularies are POWERFUL. Patterns allow you to say more with less. Talking at the pattern level allows you to stay “in the design” longer. Shared vocabularies can turbo charge your development team. Shared vocabularies encourage more junior developers to get up to speed.
  61. 61. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 61 How To Use Design Pattern?
  62. 62. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 62 Basic Design Patterns The Strategy Pattern The Observer Pattern The Factory Pattern The Singleton Pattern
  63. 63. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 63 The Strategy Pattern The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Sample Project: The game can show a large variety of duck species swimming and making quacking sounds. Using standard OO techniques (e.g: inheritance, interface, abstract classes…) Using Design Pattern.
  64. 64. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 64 Using Standard OO Techniques
  65. 65. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 65 Using Standard OO Techniques Needing fly for Duck???  Fail!!!
  66. 66. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 66 Using Standard OO Techniques Using Interfaces  needing to override for every subclasses  Duplicated code!!!
  67. 67. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 67 Using Design Pattern
  68. 68. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 68 Using Design Pattern
  69. 69. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 69 Using Design Pattern The key is that a Duck will now delegate its flying and quacking behavior, instead of using quacking and flying methods defined in the Duck class (or subclass).
  70. 70. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 70 Using Design Pattern
  71. 71. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 71 Using Design Pattern
  72. 72. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 72 Design Pattern Toolbox OO Basic •Abstraction •Encapsulation •Polymorphism •Inheritance OO Principle •Encapsulate what varies. •Favor composition over inheritence. •Program to interfaces, not implementations. OO Pattern •Rely on OO basics and principles. •Strategy- defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
  73. 73. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 73 Basic Design Patterns The Strategy Pattern The Observer Pattern The Factory Pattern The Singleton Pattern
  74. 74. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 74 The Observer Pattern “ Keep your Objects in the know” This pattern keeps your objects in the know when something they might care about happens. Objects can even decide at runtime whether they want to be kept informed. Sample: Internet-based Weather Monitoring Station The weather station will be based on our patent pending WeatherData object, which tracks current weather conditions (temperature, humidity, and barometric pressure). The application is created to provides three display elements: current conditions, weather statistics and a simple forecast, all updated in real time.
  75. 75. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 75 The Weather Monitoring App Overview
  76. 76. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 76 The Weather Monitoring App Fist implementation
  77. 77. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 77 The Weather Monitoring App What is wrong in this implementation?
  78. 78. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 78 The Observer Pattern Idea Publishers + Subscribers = Observer Pattern The publisher the SUBJECT and the subscribers the OBSERVERS
  79. 79. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 79 The Observer Pattern defined The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.
  80. 80. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 80 An Observer Pattern Implementation
  81. 81. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 81 Benefit of Observer Pattern??? The Observer Pattern provides an object design where subjects and observers are loosely coupled. The only thing the subject knows about an observer is that it implements a certain interface. We can add new observers at any time. We never need to modify the subject to add new types of observers. We can reuse subjects or observers independently of each other. Changes to either the subject or an observer will not affect the other.
  82. 82. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 82 Designing the Weather Station a
  83. 83. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 83 Implementing the Weather Station
  84. 84. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 84 Implementing the Subject Interface
  85. 85. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 85 Implementing the Observer Interface
  86. 86. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 86 Design Pattern Toolbox OO Basic •Abstraction •Encapsulation •Polymorphism •Inheritance OO Principle •Encapsulate what varies. •Favor composition over inheritence. •Program to interfaces, not implementations. •Strive for loosely coupled designs between objects that interact OO Pattern •Rely on OO basics and principles. •Observer- defines a one- to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
  87. 87. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 87 Observer Pattern Highlight!!! The Observer Pattern defines a one-to-many relationship between objects. Subjects, or as we also know them, Observables, update Observers using a common interface. Observers are loosely coupled in that the Observable knows nothing about them, other than that they implement the Observer Interface. You can push or pull data from the Observable when using the pattern (pull is considered more “correct”). Don’t depend on a specific order of notification for your Observers.
  88. 88. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 88 Design Principle Challenge Identify the aspects of your application that vary and separate them from what stays the same. Program to an interface, not an implementation. Favor composition over inheritance.
  89. 89. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 89 Basic Design Patterns The Strategy Pattern The Observer Pattern The Factory Pattern The Singleton Pattern
  90. 90. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 90 4. The Factory Pattern “Baking with OO Goodness” Get ready to bake some loosely coupled OO designs. There is more to making objects than just using the new operator. The ways to create objects Simple Factory/Static Factory Factory Method Pattern •Dependency Injection (DI) Abstract Factory Pattern When you see “new”, think “concrete”.
  91. 91. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 91 Sample Code “Creation a Duck instance” What’s happen when updating or extending the code? Open the code and examine what needs to be added or deleted. This kind of code ends up is several parts of the application making maintenance and update more difficult and error –prone.
  92. 92. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 92 Pizza Making Order “Support: CheesePizza, GreekPizza, PepperoniPizza”
  93. 93. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 93 Pizza Making Order “What’s happen when adding more pizza type?” Messing up on orderPizza() method???
  94. 94. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 94 Encapsulating Object Creation “Simple Factory/Static Factory”
  95. 95. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 95 Pizza Making Order “With Simple Factory”
  96. 96. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 96 The Simple Factory Defined The Simple Factory isn’t actually a Design Pattern; it’s more of a programming idiom.  But it is commonly used
  97. 97. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 97 Extending for Pizza Store
  98. 98. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 98 Factory Method Pattern The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  99. 99. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 99 New Pizza Store “Applying Factory Method Pattern”
  100. 100. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 100 New Pizza Store “Applying Factory Method Pattern”
  101. 101. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 101 New Pizza Store “Applying Factory Method Pattern”
  102. 102. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 102 The Dependency Inversion Principle Design Principle: Depend upon abstractions (interface, abstract, or super classes). Do not depend upon concrete classes. This principle is similar with “Program to an interface, not an implementation”.
  103. 103. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 103 Abstract Factory Pattern The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
  104. 104. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 104 New PizzaStore... “Applying Abstract Factory Pattern” All Objectville’s Pizzas are made from the same components, but each region has a different implementation of those components.
  105. 105. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 105 New PizzaStore... “Applying Abstract Factory Pattern”
  106. 106. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 106 PizzaStore Class Diagram
  107. 107. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 107 Factory Method & Abstract Factory Compared!!!
  108. 108. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 108 Design Pattern Toolbox OO Basic •Abstraction •Encapsulation •Polymorphism •Inheritance OO Principle •Encapsulate what varies. •Favor composition over inheritence. •Program to interfaces, not implementations. •Depend on abstractions. Do not depend on concrete classes. OO Pattern •Rely on OO basics and principles. •Factory Method- Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to the subclasses. •Abstract Factory- Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
  109. 109. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 109 Factory Pattern Highlight!!! All factories encapsulate object creation. Simple Factory, while not a bona fide design pattern, is a simple way to decouple your clients from concrete classes. Factory Method relies on inheritance: object creation is delegated to subclasses which implement the factory method to create objects. Abstract Factory relies on object composition: object creation is implemented in methods exposed in the factory interface. All factory patterns promote loose coupling by reducing the dependency of your application on concrete classes. The intent of Factory Method is to allow a class to defer instantiation to its subclasses. The intent of Abstract Factory is to create families of related objects without having to depend on their concrete classes. The Dependency Inversion Principle guides us to avoid dependencies on concrete types and to strive for abstractions. Factories are a powerful technique for coding to abstractions, not concrete classes
  110. 110. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 110 Basic Design Patterns The Strategy Pattern The Observer Pattern The Factory Pattern The Singleton Pattern
  111. 111. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 111 5. The Singleton Pattern “One of a Kind Objects” There is ONE and ONLY ONE object/instance to serve all requests. There are many objects, the program will run into all sorts of problems like incorrect behavior, overuse of resource, or inconsistent results (e.g: Thread Pools, Caches, Dialog Boxes, Object that handle preferences and registry setting, objects used for logging,…)
  112. 112. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 112 The Singleton Pattern “A Implementation”
  113. 113. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 113 Singleton Pattern Defined The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it. The class will manage a single instance of itself. The class prevents any other class from creating a new instance on its own. The class provides a global access point to the instance.
  114. 114. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 114 Dealing with Multithreading Using synchronized keyword to avoid dead lock in multi-threading.
  115. 115. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 115 Design Pattern Toolbox OO Basic •Abstraction •Encapsulation •Polymorphism •Inheritance OO Principle •Encapsulate what varies. •Favor composition over inheritence. •Program to interfaces, not implementations. OO Pattern •Rely on OO basics and principles. •Singleton- Ensure a one instance and provide a global point of access to it.
  116. 116. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 116 Singleton Pattern Highlight!!! The Singleton Pattern ensures you have at most one instance of a class in the application. The Singleton Pattern also provides a global access point to that instance. Java’s implementation of the Singleton Pattern makes use of a private constructor, a static method combined with a static variable. Examine your performance and resource constraints and carefully choose an appropriate Singleton implementation for multithreaded applications (and you should consider all applications multithreaded!). Beware of the double-checked locking implementation. Be careful if you are using multiple class loaders; this could defeat the Singleton implementation and result in multiple instances.
  117. 117. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 117 Sample: Voice Control Wrapper The system uses third party for voice control module. We plan to user other third party voice control in the future, so needing to design a wrapper package to avoid impaction when changing. How to do this ones?
  118. 118. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 118 Sample: Voice Control Wrapper Package Diagram
  119. 119. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 119 Sample: Voice Control Wrapper Classes Diagram
  120. 120. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 120 Basic Design Pattern Book
  121. 121. © FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/4 121 Q & A

×