SlideShare a Scribd company logo
Software PatternsJoseph Bonello
MotivationBuilding software using new frameworks is more complexAnd expensiveThere are many methodologies and frameworks to help developers build enterprise applicationThe main problems are:Changes in business logicTechnology updatesMaintenanceBuilding software is difficultBuilding reusable software is even harder!
Why Patterns?We need a common, tried-and-tested way of building and testing softwareEspecially in those areas where common problems recurThe aim is to make it easier to change and maintain softwareOther aimsDevelopers adopt a common design principleDon’t waste time “hacking” your way into a solutionReference on structures that get the work done efficiently
Patterns and Anti-patternsA pattern is a general, re-usable solution to a common problem in software designGamma, Erich; Richard Helm, Ralph Johnson, and John Vlissides (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN 0-201-63361-2 (Gang-Of-Four Book)An anti-pattern is a commonly used pattern but is counterproductive or ineffective in practiceExperienced OO designers, in general, do not try to solve a problem from first principlesInstead, they prefer to reuse a solution that has worked in the past
What constitutes a pattern?A Pattern has 4 essential elements:A pattern name: Used to refer to a description of a design problem, its solutions and consequences using a descriptive alias.  The alias allows us to communicate with other and design at a higher level of abstraction.The problem: It describes when to apply the pattern. It describes the context of the problem such as class/object structures symptomatic of bad design or a list of conditions that must be met before applying the pattern.The solution: describes the elements that make up the design, the relationships, responsibilities and collaborations. It does not describe a concrete implementation. It is an abstract description of the general arrangement that will solve the problem.The consequences: refer to the results and trade-offs or applying the pattern. They are used to judge the costs and benefits of applying the pattern. Consequences include impact on system flexibility, extensibility and portability.
Categories of PatternsCreational patternsDeal with object creation mechanismsStructural patternsEase the design of defining relationships between entitiesBehavioral patternsUsed to identify communication patterns between objects and increase flexibility when carrying out this communication
Creational PatternsWe shall be looking at the following Creational PatternsSingleton PatternAbstract Factory (Kit) Pattern
Structural PatternsIn this section, we’ll discuss the following patternsAdapter (or Wrapper) PatternBridge PatternComposite PatternDecorator PatternFaçade Pattern
Behavioural PatternsThese are some common behavioural patterns:Iterator PatternObserver PatternStrategy Pattern
Creational PatternsWe shall be looking at the following Creational PatternsSingleton PatternAbstract Factory (Kit) Pattern
The Singleton Pattern IProvides a single object throughout the lifetime of an applicationProvides a single access point to the objectAn example would be to have one database connection per client applicationUsed when:There must only be one instance of a classClients need one single way of accessing the instance
The Singleton Pattern IIBenefits:Controlled access to sole instance (or multiple instances)Avoids “global variables” in namespacePermits SubclassingMore flexible than static member and methods
Abstract Factory (Kit) IProvide an interface for creating families of related or dependent object without specifying their concrete classesUsed to de-couple clients from a particular concrete implementationExample: Different implementations of handling an order’s costs (e.g. TaxCalculator(EU,USA, CN,etc), shipping costs, etc)
Abstract Factory (Kit) II
Abstract Factory (Kit) IIIUse the Abstract Factory pattern when a system should be independent of how its products are created, composed, and represented.  a system should be configured with one of multiple families of products.  a family of related product objects is designed to be used together, and you need to enforce this constraint.  you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.
Abstract Factory (Kit) IVBenefits:Isolates concrete classesAllows to change product family easilyPromotes consistency among productsFactory usually a Singleton; ideally create<Object> should have a type parameter to make it extensible
Structural PatternsIn this section, we’ll discuss the following patternsAdapter (or Wrapper) PatternBridge PatternComposite PatternDecorator PatternFaçade Pattern
Adapter (Wrapper) IConvert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.ExampleMerging a new library with an old library you discover two methods with the same name but different parameters
Adapter (Wrapper) IIBenefits:Allow two or more incompatible objects to communicate and interact.Improves reusability of older functionality.
Adapter (Wrapper) IIIUse when:When you want to use an existing class, and its interface does not match the interface you need.When you want to create a reusable class that cooperates with unrelated or onforeseen classes, classes that don't necessarily have compatible interfaces.When you want to use an object in an environment that expects an interface that is diferent from the object's interface.When you must ensure interface translation among multiple sources.
Bridge (Handle) Pattern IUsed to decouple an abstraction from its implementation so that the two can vary independentlyWhen an abstraction (abstract class) can have several implementations, the usual way to accommodate them is to use inheritanceThis isn’t always a flexible approach because the implementation binds to the abstraction permanentlyUse the pattern when:You want to avoid a permanent binding between an abstraction and its implementationBoth the abstractions and the implementations should be extensible by sub-classingChanges in the implementation of an abstraction should not impact clients
Bridge (Handle) Pattern IIUse the pattern when (cont):You have a class hierarchy that proliferates because it needs to adapt to various specific implementationsYou want to share an implementation among multiple objects but you want to keep the fact hidden from the client.
Bridge (Handle) Pattern IIIKnown usesGUI frameworks as discussed previously.Persistence FrameworksConsequences:Implementation is not bound permanently to an interfaceEliminates compile time dependencies (no recompilation of abstract class)Decoupling encourages layering, therefore a better structured systemImproved extensibilityHiding implementation details from clients
Composite pattern IUsed to compose objects into tree structures to represent part-whole hierarchies.  Clients treat individual objects and compositions of objects uniformlyExampleConsider graphics applications that allow users to build complex diagrams out of simple components which can be grouped into more complex onesA simple implementation would define classes for graphical primitives and other classes that act as containers for these primitivesProblem: code using these classes must treat primitives and objects differentlyThe distinction increases the complexity of the systemThe pattern uses recursive composition so clients do not make this distinction
Composite pattern IIUse the pattern when:You want to represent part-whole hierarchies of objectsYou want clients to be able to ignore differences between compositions of objects and individual objects
Composite pattern IIIExampleConsequencesDefine class hierarchies consisting of primitive objects and composite objectsSimplifies the client’s architectureSimplifies the process of adding new componentsThe design can be overly general (disadvantage)
Decorator (WRAPPER) Pattern IDecorator is used to attach responsibilities to an object dynamicallyDecorators provide a flexible alternative to sub-classing for extending functionalityWhy use it?We use it when we need to add responsibilities to individual objects, not the entire class (e.g. adding borders or scrollbars to a visual widget)If you use inheritance will affect every instance which will not allow it to vary the choice as it is statically linkedThe solution is to add the object, called the decorator or wrapper, within another that adds the required property
Decorator (WRAPPER) Pattern IIUse the DecoratorTo add responsibilities to individual objects dynamically and transparentlyTo withdraw responsibilities from the objectWhen extending by sub-classing is impractical or not permittedA large number of independent extensions would result in an explosion of classesA class definition may be hidden or sealed (final)
Decorator (WRAPPER) Pattern IIIConsequencesMore flexible than static inheritanceEasier to add a property twice (e.g. a widget with a double border)Avoids feature-laden classes up in the hierarchy, reducing complexity. Features are added incrementally with new decorator objectsThe decorator and its component are identical, the decorator is a transparent enclosure similar to a photograph frameLots of little objects (disadvantage), difficult to learn and debugUsed frequently in UI Toolkits and in the implementation of IO stream classes
Façade Pattern IProvides a unified interface to a set of interfaces in a subsystemDefines a higher level interface that makes the subsystem easier to useStructuring a system into subsystems helps reduce complexityCommon design goal is to minimise communication and dependency between subsystemsFaçade objects provides a single, simplified interface to more general facilities of the sub-system
Façade Pattern IIExample: Programming environment providing access to its compiler subsystemHigher level interface shields clients from intricate details of different parts of compiler by allowing access to specific functionality of different subpartsUse Façade when:Provide a simple interface to a complex systemThere are many dependencies between clients and the implementation classes of an abstraction – Façade decouples the sub-system from clientsLayer your subsystems. Façade defines the entry to each subsystem layer
Façade Pattern IIIConsequencesShields clients from sub-system componentsPromotes weak coupling between sub-system and its clientsReduces compilation dependenciesDoes not prevent applications from using subsystem classes if they need to
Behavioural PatternsThese are some common behavioural patterns:Iterator PatternObserver PatternStrategy Pattern
Iterator (Cursor) Pattern IProvides a way to access the elements of an aggregate object sequentially without exposing its underlying representationAn aggregate object (e.g. List) should give you a way to access its elements without exposing its structureYou might want to traverse the list in many ways, but you want to keep the design and implementation of the List cleanThe idea of the pattern is to take the responsibility for accessing and traversing the list using at iterator objectThe iterator keeps track of the current elementThe List is responsible for creating its own iterator, possibly using a Factory to generalise the operation
Iterator (Cursor) Pattern IIUse this pattern when you wantTo access an aggregate object’s contents without exposing its internal representationSupport multiple traversals of aggregate objectsProvide a uniform interface for traversing different aggregate structures
Iterator (Cursor) Pattern IIIConsequences of using this patternSupports variations in the traversal of an aggregateSimplify the aggregate interfaceMode than one traversal can be pending on the same aggregateKnown uses: Collection classes (Lists, Vectors, etc)
Observer (dependents) Pattern IDefines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automaticallyWhen partitioning a system into a collection of cooperating classes, one needs to maintain consistency between related objectsNote that tightly coupling class is not a solution because it reduces reusabilityThe observer pattern describes how to establish common relationships between objectsThe key objects are the subject and the observerAll observer are notified when the subject changes (publish-subscribe model)
Observer (dependents) Pattern IIUsed whenAbstraction has two aspects, one dependent on the other. Encapsulate the objects separately and reuse them independentlyWhen a change to one object requires changing the others, and you do not know how many objects to changeWhen an object needs to be able to notify other objects without making assumptions about who these objects are (not tightly coupled)
Observer (dependents) Pattern IIIConsequencesAbstract coupling between Subject and Observer. Subject knows that it has a list of observers conforming to the observer interface, it does not know the concrete class of the observer – minimal couplingSupport for broadcast communicationUnexpected updated (disadvantage). Since observers have no knowledge of other observers, changing the subject might result in undesired updates
Strategy (Policy) Pattern IDefine a family of algorithms that encapsulate one another and make them interchangeableStrategy lets the algorithm vary independently of the client that uses themExample: Many algorithms exist for breaking a stream of text into lines. Hard-wiring all algorithms into the classes that require them is not desirable becauseClient get overly complexDifferent algorithms will be appropriate at different timesDifficult to add new algorithms and vary existing ones
Strategy (Policy) Pattern IIUse this pattern whenMany related classes differ only in their behaviourNeed different variants of an algorithmAn algorithm uses data that clients shouldn’t know about (avoid exposing complex, algorithm-specific data structures)A class defines many behaviours that appear as multiple conditional statements in its operators
Strategy (Policy) Pattern IIIConsequencesFamilies of related algorithms. Hierarchies of Strategy classes define a family of algorithms that can be reusedAn alternative to sub-classing, which is easier to switch to, understand and extendStrategies eliminate conditional statementsProvides a choice of implementationsClients must be aware of different strategies (disadvantage)Communication overhead between Strategy and Context (Strategy interface is shared, so some simple concrete classes may use little or none of the parameters passes to them. Tightly couple context and strategy to solve this problem)Increased number of objects
OtherModel-View-Controller (MVC)This pattern isolates domain logic from the user interfaceThe model manages the behaviour and data of the application domain, The view renders the model into a form suitable for interaction, typically a user interface element. The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input.Sometimes considered a framework
Further ReadingGamma, E., Helm, R., Johnson, R., & Vlissides, J. (2007). Design Patterns: Elements of Reusable Object-Oriented Software. USA: Addison-Wesley Professional (ISBN 0-201-63361-2)McConell, S. (2004). Code Complete: A Practical Handbook of Software Construction. USA: MICROSOFT PRESS (ISBN 0-735-61967-0)Alur, D., Malks, D., & Crupi, J. (2003). Core J2EE Patterns: Best Practices and Design Strategies. USA: Prentice Hall (ISBN 0-131-42246-4)http://www.dofactory.com/Patterns/Patterns.aspxhttp://www.oodesign.com

More Related Content

PPT
Design patterns
PDF
Design patterns
PPTX
Composite design pattern
PPTX
Design patterns
PPT
Software Design Patterns
PDF
Software Design Patterns. Part I :: Structural Patterns
PPT
Design Patterns
PPT
Structural patterns
Design patterns
Design patterns
Composite design pattern
Design patterns
Software Design Patterns
Software Design Patterns. Part I :: Structural Patterns
Design Patterns
Structural patterns

What's hot (19)

PPTX
Sequence diagrams in UML
PPTX
Creational pattern
PPT
Software Architecture and Project Management module III : PATTERN OF ENTERPRISE
PPT
Software Design Patterns
PPT
Design Pattern For C# Part 1
PPS
Vb net xp_03
DOCX
Design Pattern Notes: Nagpur University
PPTX
Design patterns creational patterns
PPTX
Behavioral pattern By:-Priyanka Pradhan
PPTX
PATTERNS04 - Structural Design Patterns
PPTX
The SOLID Principles Illustrated by Design Patterns
PPTX
PATTERNS02 - Creational Design Patterns
PDF
Design UML diagrams
PPT
P Training Presentation
DOCX
Design patterns
PPTX
PATTERNS03 - Behavioural Design Patterns
PPTX
Factory method, strategy pattern & chain of responsibilities
PPT
Composite Pattern
PPTX
Factory method & strategy pattern
Sequence diagrams in UML
Creational pattern
Software Architecture and Project Management module III : PATTERN OF ENTERPRISE
Software Design Patterns
Design Pattern For C# Part 1
Vb net xp_03
Design Pattern Notes: Nagpur University
Design patterns creational patterns
Behavioral pattern By:-Priyanka Pradhan
PATTERNS04 - Structural Design Patterns
The SOLID Principles Illustrated by Design Patterns
PATTERNS02 - Creational Design Patterns
Design UML diagrams
P Training Presentation
Design patterns
PATTERNS03 - Behavioural Design Patterns
Factory method, strategy pattern & chain of responsibilities
Composite Pattern
Factory method & strategy pattern
Ad

Viewers also liked (17)

PDF
Edited Treatment for 'Tamam Shud'
PDF
Zaproszenie
PDF
Cast and Crew List
PPTX
Sjr education
PDF
Jim Shelton Recommendation
PPTX
Современная бизнес реальность как вызов для риэлторской услуги.Pptx
PPTX
LYNKOS Intro
PDF
Certificate
PPTX
LYNKOS Overview - Financial Institutions
PPT
μαντω μαυρογενους
PDF
Advantage MRI - Letter of Recommendation 2016
DOCX
'Help Wanted' script
PPTX
Enfermedad de quervain
PPT
Testes ágeis: saindo da zona de conforto
PDF
Conhecendo as funções analogread, analogwrite e analogreference
PDF
Awareness of Children Internet Addiction
PDF
Bits and Bytes
Edited Treatment for 'Tamam Shud'
Zaproszenie
Cast and Crew List
Sjr education
Jim Shelton Recommendation
Современная бизнес реальность как вызов для риэлторской услуги.Pptx
LYNKOS Intro
Certificate
LYNKOS Overview - Financial Institutions
μαντω μαυρογενους
Advantage MRI - Letter of Recommendation 2016
'Help Wanted' script
Enfermedad de quervain
Testes ágeis: saindo da zona de conforto
Conhecendo as funções analogread, analogwrite e analogreference
Awareness of Children Internet Addiction
Bits and Bytes
Ad

Similar to Software Patterns (20)

PPTX
Design patterns
PPT
Software Design Patterns
PPTX
PPTX
Facade pattern presentation(.pptx)
PPTX
Architecture and design
PPT
Introduction To Design Patterns
PPT
Design Patterns
PPT
chapter 5 Objectdesign.ppt
PPT
Object Oriented Analysis and Design
PPT
Design pattern
PPTX
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
PPT
Encapsulation
PDF
Nina Grantcharova - Approach to Separation of Concerns via Design Patterns
DOCX
Patterns (contd)Software Development ProcessDesign patte.docx
PPTX
UNIT IV DESIGN PATTERNS.pptx
PPTX
Cs 1023 lec 8 design pattern (week 2)
PPTX
Design patterns
PDF
designpatterns-.pdf
PPTX
OOPSDesign PPT ( introduction to opps and design (
PPTX
Design pattern (week 2)
Design patterns
Software Design Patterns
Facade pattern presentation(.pptx)
Architecture and design
Introduction To Design Patterns
Design Patterns
chapter 5 Objectdesign.ppt
Object Oriented Analysis and Design
Design pattern
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Encapsulation
Nina Grantcharova - Approach to Separation of Concerns via Design Patterns
Patterns (contd)Software Development ProcessDesign patte.docx
UNIT IV DESIGN PATTERNS.pptx
Cs 1023 lec 8 design pattern (week 2)
Design patterns
designpatterns-.pdf
OOPSDesign PPT ( introduction to opps and design (
Design pattern (week 2)

Recently uploaded (20)

PPTX
Spectroscopy.pptx food analysis technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Encapsulation theory and applications.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Getting Started with Data Integration: FME Form 101
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Tartificialntelligence_presentation.pptx
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Electronic commerce courselecture one. Pdf
Spectroscopy.pptx food analysis technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Spectral efficient network and resource selection model in 5G networks
MYSQL Presentation for SQL database connectivity
Encapsulation theory and applications.pdf
cuic standard and advanced reporting.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Getting Started with Data Integration: FME Form 101
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Dropbox Q2 2025 Financial Results & Investor Presentation
20250228 LYD VKU AI Blended-Learning.pptx
Tartificialntelligence_presentation.pptx
Accuracy of neural networks in brain wave diagnosis of schizophrenia
MIND Revenue Release Quarter 2 2025 Press Release
The Rise and Fall of 3GPP – Time for a Sabbatical?
Assigned Numbers - 2025 - Bluetooth® Document
Per capita expenditure prediction using model stacking based on satellite ima...
Big Data Technologies - Introduction.pptx
Electronic commerce courselecture one. Pdf

Software Patterns

  • 2. MotivationBuilding software using new frameworks is more complexAnd expensiveThere are many methodologies and frameworks to help developers build enterprise applicationThe main problems are:Changes in business logicTechnology updatesMaintenanceBuilding software is difficultBuilding reusable software is even harder!
  • 3. Why Patterns?We need a common, tried-and-tested way of building and testing softwareEspecially in those areas where common problems recurThe aim is to make it easier to change and maintain softwareOther aimsDevelopers adopt a common design principleDon’t waste time “hacking” your way into a solutionReference on structures that get the work done efficiently
  • 4. Patterns and Anti-patternsA pattern is a general, re-usable solution to a common problem in software designGamma, Erich; Richard Helm, Ralph Johnson, and John Vlissides (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN 0-201-63361-2 (Gang-Of-Four Book)An anti-pattern is a commonly used pattern but is counterproductive or ineffective in practiceExperienced OO designers, in general, do not try to solve a problem from first principlesInstead, they prefer to reuse a solution that has worked in the past
  • 5. What constitutes a pattern?A Pattern has 4 essential elements:A pattern name: Used to refer to a description of a design problem, its solutions and consequences using a descriptive alias. The alias allows us to communicate with other and design at a higher level of abstraction.The problem: It describes when to apply the pattern. It describes the context of the problem such as class/object structures symptomatic of bad design or a list of conditions that must be met before applying the pattern.The solution: describes the elements that make up the design, the relationships, responsibilities and collaborations. It does not describe a concrete implementation. It is an abstract description of the general arrangement that will solve the problem.The consequences: refer to the results and trade-offs or applying the pattern. They are used to judge the costs and benefits of applying the pattern. Consequences include impact on system flexibility, extensibility and portability.
  • 6. Categories of PatternsCreational patternsDeal with object creation mechanismsStructural patternsEase the design of defining relationships between entitiesBehavioral patternsUsed to identify communication patterns between objects and increase flexibility when carrying out this communication
  • 7. Creational PatternsWe shall be looking at the following Creational PatternsSingleton PatternAbstract Factory (Kit) Pattern
  • 8. Structural PatternsIn this section, we’ll discuss the following patternsAdapter (or Wrapper) PatternBridge PatternComposite PatternDecorator PatternFaçade Pattern
  • 9. Behavioural PatternsThese are some common behavioural patterns:Iterator PatternObserver PatternStrategy Pattern
  • 10. Creational PatternsWe shall be looking at the following Creational PatternsSingleton PatternAbstract Factory (Kit) Pattern
  • 11. The Singleton Pattern IProvides a single object throughout the lifetime of an applicationProvides a single access point to the objectAn example would be to have one database connection per client applicationUsed when:There must only be one instance of a classClients need one single way of accessing the instance
  • 12. The Singleton Pattern IIBenefits:Controlled access to sole instance (or multiple instances)Avoids “global variables” in namespacePermits SubclassingMore flexible than static member and methods
  • 13. Abstract Factory (Kit) IProvide an interface for creating families of related or dependent object without specifying their concrete classesUsed to de-couple clients from a particular concrete implementationExample: Different implementations of handling an order’s costs (e.g. TaxCalculator(EU,USA, CN,etc), shipping costs, etc)
  • 15. Abstract Factory (Kit) IIIUse the Abstract Factory pattern when a system should be independent of how its products are created, composed, and represented. a system should be configured with one of multiple families of products. a family of related product objects is designed to be used together, and you need to enforce this constraint. you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.
  • 16. Abstract Factory (Kit) IVBenefits:Isolates concrete classesAllows to change product family easilyPromotes consistency among productsFactory usually a Singleton; ideally create<Object> should have a type parameter to make it extensible
  • 17. Structural PatternsIn this section, we’ll discuss the following patternsAdapter (or Wrapper) PatternBridge PatternComposite PatternDecorator PatternFaçade Pattern
  • 18. Adapter (Wrapper) IConvert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.ExampleMerging a new library with an old library you discover two methods with the same name but different parameters
  • 19. Adapter (Wrapper) IIBenefits:Allow two or more incompatible objects to communicate and interact.Improves reusability of older functionality.
  • 20. Adapter (Wrapper) IIIUse when:When you want to use an existing class, and its interface does not match the interface you need.When you want to create a reusable class that cooperates with unrelated or onforeseen classes, classes that don't necessarily have compatible interfaces.When you want to use an object in an environment that expects an interface that is diferent from the object's interface.When you must ensure interface translation among multiple sources.
  • 21. Bridge (Handle) Pattern IUsed to decouple an abstraction from its implementation so that the two can vary independentlyWhen an abstraction (abstract class) can have several implementations, the usual way to accommodate them is to use inheritanceThis isn’t always a flexible approach because the implementation binds to the abstraction permanentlyUse the pattern when:You want to avoid a permanent binding between an abstraction and its implementationBoth the abstractions and the implementations should be extensible by sub-classingChanges in the implementation of an abstraction should not impact clients
  • 22. Bridge (Handle) Pattern IIUse the pattern when (cont):You have a class hierarchy that proliferates because it needs to adapt to various specific implementationsYou want to share an implementation among multiple objects but you want to keep the fact hidden from the client.
  • 23. Bridge (Handle) Pattern IIIKnown usesGUI frameworks as discussed previously.Persistence FrameworksConsequences:Implementation is not bound permanently to an interfaceEliminates compile time dependencies (no recompilation of abstract class)Decoupling encourages layering, therefore a better structured systemImproved extensibilityHiding implementation details from clients
  • 24. Composite pattern IUsed to compose objects into tree structures to represent part-whole hierarchies. Clients treat individual objects and compositions of objects uniformlyExampleConsider graphics applications that allow users to build complex diagrams out of simple components which can be grouped into more complex onesA simple implementation would define classes for graphical primitives and other classes that act as containers for these primitivesProblem: code using these classes must treat primitives and objects differentlyThe distinction increases the complexity of the systemThe pattern uses recursive composition so clients do not make this distinction
  • 25. Composite pattern IIUse the pattern when:You want to represent part-whole hierarchies of objectsYou want clients to be able to ignore differences between compositions of objects and individual objects
  • 26. Composite pattern IIIExampleConsequencesDefine class hierarchies consisting of primitive objects and composite objectsSimplifies the client’s architectureSimplifies the process of adding new componentsThe design can be overly general (disadvantage)
  • 27. Decorator (WRAPPER) Pattern IDecorator is used to attach responsibilities to an object dynamicallyDecorators provide a flexible alternative to sub-classing for extending functionalityWhy use it?We use it when we need to add responsibilities to individual objects, not the entire class (e.g. adding borders or scrollbars to a visual widget)If you use inheritance will affect every instance which will not allow it to vary the choice as it is statically linkedThe solution is to add the object, called the decorator or wrapper, within another that adds the required property
  • 28. Decorator (WRAPPER) Pattern IIUse the DecoratorTo add responsibilities to individual objects dynamically and transparentlyTo withdraw responsibilities from the objectWhen extending by sub-classing is impractical or not permittedA large number of independent extensions would result in an explosion of classesA class definition may be hidden or sealed (final)
  • 29. Decorator (WRAPPER) Pattern IIIConsequencesMore flexible than static inheritanceEasier to add a property twice (e.g. a widget with a double border)Avoids feature-laden classes up in the hierarchy, reducing complexity. Features are added incrementally with new decorator objectsThe decorator and its component are identical, the decorator is a transparent enclosure similar to a photograph frameLots of little objects (disadvantage), difficult to learn and debugUsed frequently in UI Toolkits and in the implementation of IO stream classes
  • 30. Façade Pattern IProvides a unified interface to a set of interfaces in a subsystemDefines a higher level interface that makes the subsystem easier to useStructuring a system into subsystems helps reduce complexityCommon design goal is to minimise communication and dependency between subsystemsFaçade objects provides a single, simplified interface to more general facilities of the sub-system
  • 31. Façade Pattern IIExample: Programming environment providing access to its compiler subsystemHigher level interface shields clients from intricate details of different parts of compiler by allowing access to specific functionality of different subpartsUse Façade when:Provide a simple interface to a complex systemThere are many dependencies between clients and the implementation classes of an abstraction – Façade decouples the sub-system from clientsLayer your subsystems. Façade defines the entry to each subsystem layer
  • 32. Façade Pattern IIIConsequencesShields clients from sub-system componentsPromotes weak coupling between sub-system and its clientsReduces compilation dependenciesDoes not prevent applications from using subsystem classes if they need to
  • 33. Behavioural PatternsThese are some common behavioural patterns:Iterator PatternObserver PatternStrategy Pattern
  • 34. Iterator (Cursor) Pattern IProvides a way to access the elements of an aggregate object sequentially without exposing its underlying representationAn aggregate object (e.g. List) should give you a way to access its elements without exposing its structureYou might want to traverse the list in many ways, but you want to keep the design and implementation of the List cleanThe idea of the pattern is to take the responsibility for accessing and traversing the list using at iterator objectThe iterator keeps track of the current elementThe List is responsible for creating its own iterator, possibly using a Factory to generalise the operation
  • 35. Iterator (Cursor) Pattern IIUse this pattern when you wantTo access an aggregate object’s contents without exposing its internal representationSupport multiple traversals of aggregate objectsProvide a uniform interface for traversing different aggregate structures
  • 36. Iterator (Cursor) Pattern IIIConsequences of using this patternSupports variations in the traversal of an aggregateSimplify the aggregate interfaceMode than one traversal can be pending on the same aggregateKnown uses: Collection classes (Lists, Vectors, etc)
  • 37. Observer (dependents) Pattern IDefines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automaticallyWhen partitioning a system into a collection of cooperating classes, one needs to maintain consistency between related objectsNote that tightly coupling class is not a solution because it reduces reusabilityThe observer pattern describes how to establish common relationships between objectsThe key objects are the subject and the observerAll observer are notified when the subject changes (publish-subscribe model)
  • 38. Observer (dependents) Pattern IIUsed whenAbstraction has two aspects, one dependent on the other. Encapsulate the objects separately and reuse them independentlyWhen a change to one object requires changing the others, and you do not know how many objects to changeWhen an object needs to be able to notify other objects without making assumptions about who these objects are (not tightly coupled)
  • 39. Observer (dependents) Pattern IIIConsequencesAbstract coupling between Subject and Observer. Subject knows that it has a list of observers conforming to the observer interface, it does not know the concrete class of the observer – minimal couplingSupport for broadcast communicationUnexpected updated (disadvantage). Since observers have no knowledge of other observers, changing the subject might result in undesired updates
  • 40. Strategy (Policy) Pattern IDefine a family of algorithms that encapsulate one another and make them interchangeableStrategy lets the algorithm vary independently of the client that uses themExample: Many algorithms exist for breaking a stream of text into lines. Hard-wiring all algorithms into the classes that require them is not desirable becauseClient get overly complexDifferent algorithms will be appropriate at different timesDifficult to add new algorithms and vary existing ones
  • 41. Strategy (Policy) Pattern IIUse this pattern whenMany related classes differ only in their behaviourNeed different variants of an algorithmAn algorithm uses data that clients shouldn’t know about (avoid exposing complex, algorithm-specific data structures)A class defines many behaviours that appear as multiple conditional statements in its operators
  • 42. Strategy (Policy) Pattern IIIConsequencesFamilies of related algorithms. Hierarchies of Strategy classes define a family of algorithms that can be reusedAn alternative to sub-classing, which is easier to switch to, understand and extendStrategies eliminate conditional statementsProvides a choice of implementationsClients must be aware of different strategies (disadvantage)Communication overhead between Strategy and Context (Strategy interface is shared, so some simple concrete classes may use little or none of the parameters passes to them. Tightly couple context and strategy to solve this problem)Increased number of objects
  • 43. OtherModel-View-Controller (MVC)This pattern isolates domain logic from the user interfaceThe model manages the behaviour and data of the application domain, The view renders the model into a form suitable for interaction, typically a user interface element. The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input.Sometimes considered a framework
  • 44. Further ReadingGamma, E., Helm, R., Johnson, R., & Vlissides, J. (2007). Design Patterns: Elements of Reusable Object-Oriented Software. USA: Addison-Wesley Professional (ISBN 0-201-63361-2)McConell, S. (2004). Code Complete: A Practical Handbook of Software Construction. USA: MICROSOFT PRESS (ISBN 0-735-61967-0)Alur, D., Malks, D., & Crupi, J. (2003). Core J2EE Patterns: Best Practices and Design Strategies. USA: Prentice Hall (ISBN 0-131-42246-4)http://www.dofactory.com/Patterns/Patterns.aspxhttp://www.oodesign.com

Editor's Notes

  • #22: Code is platform-dependent. Concrete classes here have a specific implementation
  • #29: Widgets with all possible types of borders, scrollbars, etc.
  • #30: Widgets with all possible types of borders, scrollbars, etc.
  • #38: Spreadsheet – same data, different views
  • #39: Spreadsheet – same data, different views
  • #40: Spreadsheet – same data, different views