Software Patterns

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Notes on slide 1

    Low hardware traps sensor input reading electrical signals from a wire High user-visible functionality high-level policies such as phone tariffs

    Favorites, Groups & Events

    Software Patterns - Presentation Transcript

    1. Software Patterns Sudarsun Santhiappan Director – Research & Development Burning Glass Technologies Chennai 600010
    2. Coverage
      • Object Oriented Thinking
      • Diagrammatic Representation
      • Software Architecture
      • Architecture Patterns
      • Design Patterns
    3. Objectives
      • Open a window to the architecture and design patterns world, explain why are they needed and where did they came from, and give some examples and real world tastes of chosen Design Pattern and Architectures
      • Not a programming language oriented lecture, we will mainly discuss the paradigms and uses with examples in various programming languages.
    4. Programming Paradigms..
      • Block Programming
      • Procedural Programming
      • Object Oriented Programming
        • Polymorphism + Late Binding (some) + Encapsulation (some) + Inheritance
      • Component Oriented
        • Polymorphism + Really Late Binding + Real, Enforced Encapsulation + Interface Inheritance + Binary Reuse
      • SOA
    5. Types of S/W Patterns
      • design patterns (software design) [Buschmann-POSA]
        • architectural (systems design)
        • design (micro-architectures) [Gamma-GoF]
        • idioms (low level)
      • analysis patterns (recurring & reusable analysis models) [Flower]
      • organization patterns (structure of organizations/projects)
      • process patterns (software process design)
      • domain-specific patterns
    6. Overview of the UML
      • The UML is a language for
        • visualizing
        • specifying
        • constructing
        • documenting
      the artifacts of a software-intensive system
    7. Overview of the UML
      • Modeling elements
      • Relationships
      • Extensibility Mechanisms
      • Diagrams
    8. Modeling Elements
      • Structural elements
        • class, interface, collaboration, use case, active class, component, node
      • Behavioral elements
        • interaction, state machine
      • Grouping elements
        • package, subsystem
      • Other elements
        • note
    9. Relationships
      • Dependency
      • Association
      • Generalization
      • Realization
    10. Extensibility Mechanisms
      • Stereotype
      • Tagged value
      • Constraint
    11. Models, Views, and Diagrams Activity Diagrams A model is a complete description of a system from a particular perspective Models Use Case Diagrams Use Case Diagrams Use Case Diagrams Scenario Diagrams Scenario Diagrams Collaboration Diagrams State Diagrams State Diagrams Component Diagrams Component Diagrams Component Diagrams Deployment Diagrams State Diagrams State Diagrams Object Diagrams Scenario Diagrams Scenario Diagrams Statechart Diagrams Use Case Diagrams Use Case Diagrams Sequence Diagrams State Diagrams State Diagrams Class Diagrams
    12. Diagrams
      • A diagram is a view into a model
        • Presented from the aspect of a particular stakeholder
        • Provides a partial representation of the system
        • Is semantically consistent with other views
      • In the UML, there are nine standard diagrams
        • Static views: use case, class, object, component, deployment
        • Dynamic views: sequence, collaboration, statechart, activity
    13. Use Case Diagram
      • Captures system functionality as seen by users
    14. Use Case Diagram
      • Captures system functionality as seen by users
      • Built in early stages of development
      • Purpose
        • Specify the context of a system
        • Capture the requirements of a system
        • Validate a system’s architecture
        • Drive implementation and generate test cases
      • Developed by analysts and domain experts
    15. Class Diagram
      • Captures the vocabulary of a system
    16. Class Diagram
      • Captures the vocabulary of a system
      • Built and refined throughout development
      • Purpose
        • Name and model concepts in the system
        • Specify collaborations
        • Specify logical database schemas
      • Developed by analysts, designers, and implementers
    17. Object Diagram
      • Captures instances and links
    18. Object Diagram
      • Shows instances and links
      • Built during analysis and design
      • Purpose
        • Illustrate data/object structures
        • Specify snapshots
      • Developed by analysts, designers, and implementers
    19. Component Diagram
      • Captures the physical structure of the implementation
    20. Component Diagram
      • Captures the physical structure of the implementation
      • Built as part of architectural specification
      • Purpose
        • Organize source code
        • Construct an executable release
        • Specify a physical database
      • Developed by architects and programmers
    21. Deployment Diagram
      • Captures the topology of a system’s hardware
    22. Deployment Diagram
      • Captures the topology of a system’s hardware
      • Built as part of architectural specification
      • Purpose
        • Specify the distribution of components
        • Identify performance bottlenecks
      • Developed by architects, networking engineers, and system engineers
    23. Sequence Diagram
      • Captures dynamic behavior (time-oriented)
    24. Sequence Diagram
      • Captures dynamic behavior (time-oriented)
      • Purpose
        • Model flow of control
        • Illustrate typical scenarios
    25. Collaboration Diagram
      • Captures dynamic behavior (message-oriented)
    26. Collaboration Diagram
      • Captures dynamic behavior (message-oriented)
      • Purpose
        • Model flow of control
        • Illustrate coordination of object structure and control
    27. Statechart Diagram
      • Captures dynamic behavior (event-oriented)
    28. Statechart Diagram
      • Captures dynamic behavior (event-oriented)
      • Purpose
        • Model object lifecycle
        • Model reactive objects (user interfaces, devices, etc.)
    29. Activity Diagram
      • Captures dynamic behavior (activity-oriented)
    30. Activity Diagram
      • Captures dynamic behavior (activity-oriented)
      • Purpose
        • Model business workflows
        • Model operations
    31. Architecture and the UML Design View Implementation View Process View Deployment View Organization Package, subsystem Dynamics Interaction State machine Components Classes, interfaces, collaborations Active classes Nodes Use Case View Use cases
    32. Software engineering process
      • A set of partially ordered steps intended to reach a goal. In software engineering the goal is to build a software product or to enhance an existing one .
      • Architectural process
        • Sequence of activities that lead to the production of architectural artifacts:
          • A software architecture description
          • An architectural prototype
    33. System Architecture Logical View Implementation View Programmers Software management Process View Deployment View System topology Delivery, installation Communication System engineering Conceptual Physical Use Case View Conceptual Physical End-user Functionality Performance Scalability Throughput System integrators
    34. Pattern Oriented Software Architecture Patterns for Software Architecture, Distributed Systems and Resource Management
      • Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, Michael Stal. Pattern-oriented Software Architecture: System of Patterns Vol 1. John Wiley and Sons Ltd. 1996.
      • Frank Buschmann, Douglas Schmidt, Michael Stal, Hans Rohnert. Pattern-oriented Software Architecture Vol 2: Patterns for Concurrent and Networked Objects. John Wiley and Sons Ltd. 2000.
      • Michael Kircher, Prashant Jain. Pattern-Oriented Software Architecture: Patterns for Distributed Services and Components. John Wiley and Sons Ltd. 2004.
      Three types of patterns (Buschmann et al.):
      • Architectural Patterns
        • An architectural pattern expresses a fundamental structural organization for software systems or schema for software systems. It provides a set of predefined subsystems, specifies their responsibilities, and includes rules and guidelines for organizing the relationships between them.
      • Design Patterns
        • A design pattern provides a scheme for refining the subsystems or components of a software system, or the relationships between them. It describes commonly recurring structure of communicating components that solve a design problem within a particular context.
      • Idioms
        • An idiom is a low-level pattern specific to a programming language. An idiom describes how to implement particular aspects of components or the relationships between them using the features of the given language.
    35. Architecture - Definition
      • Highest level representation of a system
      • How a big system could be broken down into smaller components ?
      • Shared understanding of a system
      • How major components fit together ?
      • How components interact ?
    36. Example: Nokia MITA
      • Mobile Internet Technical Architecture
      Intranet (WLAN)/Bluetooth Web domain Internet xDSL PSTN Mobile networks GSM EDGE WCDMA Mobile domain WLAN /Bluetooth Bluetooth =Server
    37. Architecture
        Software architecture encompasses the set of significant decisions about the organization of a software system
        • selection of the structural elements and their interfaces by which a system is composed
        • behavior as specified in collaborations among those elements
        • Composition of these structural and behavioral elements into larger subsystem
        • architectural style that guides this organization
    38. Architecture Characteristics
      • usage
      • functionality
      • performance
      • resilience
      • reuse
      • comprehensibility
      • economic and technology constraints and trade offs
      • aesthetic concerns
    39. Who are the architects?
      • Experience
        • software development
        • domain
      • Pro-active, goal oriented
      • Leadership, authority
      • Architecture team
        • balance
    40. Architect
      • Not just a top level designer
          • Need to ensure feasibility
      • Not the project manager
          • But “joined at the hip”
      • Not a technology expert
          • Purpose of the system, “fit”,
      • Not a lone scientist
          • Communicator
    41. Software Architecture Team Charter
      • Defining the architecture of the software
      • Maintaining the architectural integrity of the software
      • Assessing technical risks related to the software design
      • Proposing the order and contents of the successive iterations
      • Consulting services
      • Assisting marketing for future product definition
      • Facilitating communications between project teams
    42. Architecture is making decisions The life of a software architect is a long (and sometimes painful) succession of suboptimal decisions made partly in the dark.
    43. Architectural design
      • Identify, select, and validate “architecturally significant” elements
      • Not everything is architecture
        • Main “business” classes
        • Important mechanisms
        • Processors and processes
        • Layers and subsystems
        • Interfaces
      • Produce a Software Architecture Documen
    44. Architectural design workflow
      • Select scenarios: criticality and risk
      • Identify main classes and their responsibility
      • Distribute behavio r on classes
      • Structure in subsystems, layers, define interfaces
      • Define distribution and concurrency
      • Implement architectural prototype
      • Derive tests from use cases
      • Evaluate architecture
      Iterate Use case view Logical view Deployment view Implementation view Process view
    45. Patterns
      • A pattern is a solution to a problem in a context
      • A pattern codifies specific knowledge collected from experience in a domain
      • All well-structured systems are full of patterns
        • Idioms
        • Design patterns
        • Architectural patterns
    46. Patterns - Definition
      • 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 .
      • Each pattern is a three-part rule , which expresses a relation between a certain context , a problem , and a solution .
      • GoF: The design patterns are descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context
    47. Why Patterns?
      • Patterns can be used by programmers, designers, and architects who are building applications and who want to improve either their understanding of architectural issues or their communication about them. (Fowler)
      • Patterns are common solutions to recurring problems. If you have worked in applications for a while, you may well know most of them. They are industry’s old ideas . If you are new , pattern book can help you learn about those techniques. If you are familiar with the techniques, pattern book can help you communicate and teach them to others. An important part of patterns is trying to build a common vocabulary for communication . (Fowler)
      • Patterns constitute an effort to build on the collective experience of skilled designers and software engineers. (Buschmann et al.)
      • Experts already have solutions to many recurring design problems . (Buschmann et al.)
      • Patterns capture proven solutions in an easily-available and, hopefully, well-written form (Buschmann et al.)
      • Patterns support both novices and experts in software development. (Buschmann et al.)
    48. Architectural Patterns
    49. Architectural patterns
      • Distributed  Layered
      • Event-driven  MVC
      • Frame-based  IR-centric
      • Batch  Subsumption
      • Pipes and filters  Disposable
      • Repository-centric
      • Blackboard
      • Interpreter
      • Rule-based
    50. Model View Controller
      • The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes
      • The controller changes the model
      • The View Listens to Model
      • Process Control!
    51. What is the Layers Pattern?
      • Architectural pattern that helps to structure applications that can be decomposed into groups of subtasks in which each group of subtasks is at a particular level of abstraction.
      • What is high? What is low?
      • Flow
        • requests from higher layer to lower layer
        • answers from lower layer to higher layer
        • incoming data or event notification from low to high
    52. Things to Take Care of...
      • Late source code changes should not ripple
      • Interfaces should be stable
      • Interfaces may be prescribed by a standards body
      • Parts of the system should be exchangeable
      • Design for change!
      • May be necessary to build other systems at a later date with same low-level issues
      • Similar responsibilities should be grouped to help understandability and maintainability
      • No standard component granularity
      • Complex components may need further decomposition
    53. More...
      • Crossing component boundaries may impede performance
        • substantial amount of data transferred over several boundaries
      • The system will be built by actual human beings
        • Work must be subdivided along clear boundaries
        • Architecture influences team structure and vice versa
    54. Solution
      • Structure the system into an appropriate number of layers
      • Think of lowest level as Layer 1; highest Layer N
      • This gives a conceptual view – not marching orders regarding sequence of further design
      • Within a layer, all subcomponents work at the same level of abstraction
      • Most of what Layer J provides is composed of services provided by Layer J-1, combined in a meaningful way for the application.
    55. Illustration
    56. Implementation
      • Define which of the abstraction criteria you will use
      • Determine the number of abstraction levels according to your criterion
      • Name the layers and assign tasks to each of them
      • Specify the services
      • Refine the layering
        • repeat steps 1-4 until natural, stable layering evolves
        • Finding layers is not orderly – yo-yo development
      • Specify an interface for each layer
    57. Implementation
      • Structure individual layers
      • Specify communication between adjacent layers
        • push/pull
      • Decouple adjacent layers
        • t op-down: J+1 knows about J; J can ignore J+1
        • bottom-up:
          • can use callbacks
          • can decouple the upper from the lower somewhat
      • Design an error-handling strategy
    58. Some Applications
      • Virtual Machines
      • APIs
      • Information Systems – Lower Layer is DB
        • Presentation
        • Application Logic
        • Domain Layer
        • Database
      • Operating Systems
    59. SOA
      • SOA is an architectural style whose goal is to achieve loose coupling among interacting software agents.
      • A service is a unit of work done by a service provider to achieve desired end results for a service consumer
      • in SOA, services are the mechanism by which needs and capabilities are brought together.
    60. SOA - Principles
      • Visibility – the ability for a service consumer to “see” a service provider (Awareness, willingness and Reachability)
      • Interaction - the activity of using a capability. (usually message exchange - by contracts, constraints and policies, for example Web Service Description Language)
      • Effect – the result of an interaction
      • SOAP: Simple Object Access Protocol
      • WSDL: Web Service Description Language
    61. SOA - example
    62. Idioms
    63. Guard
      • Problem
        • Want to tie key scoped behaviors to actual program scopes
          • e.g., program trace, resource acquisition/release, locking
        • However, tying functions to functions is error-prone
          • e.g., forgetting the release call, exceptional return paths
      • Solution
        • Design a special adapter class whose constructor and destructor call the key scope entry and exit behaviors
        • Create a guard object on the program call stack (in a scope)
      • Context limitations
        • Mainly limited to languages with constructor/destructor
    64. Design Patterns
    65. What are design patterns?
      • The Beginning - “Gang of four” (Gama et al 1995)
      • What's the difference between an architecture and a Design patterns?
      • Patterns sub types:
        • Creational
        • Structural
        • Behavioral
    66. Design Patterns Catalog
    67. Template Method Pattern Intent / Applicability
      • Intent
        • Define the skeleton of an algorithm, deferring some steps to subclasses.
        • Template Method lets subclasses redefine certain steps of an algorithm, without changing the algorithm’s structure.
      • Applicability – Use Template Method Pattern…
        • To implement the invariant part of an algorithm, and leave it up to subclasses to implement the part that can vary.
        • When common code in subclasses should be factored and localized in a common base class to avoid code duplication.
        • To control extensions to subclasses. (Hook operations)
    68. Template Method Pattern Participants
      • AbstractClass
        • Defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.
        • Implements a template method defining the skeleton of an algorithm. It calls primitive operations as well as other operations in the AbstractClass (or other classes).
      • ConcreteClass
        • Implements primitive operations to carry out subclass-specific steps of the algorithm.
      Note: Some concrete AbstractClass methods can also be defined. Hollywood Principle – “Don’t call us, we’ll call you.” => Parent class calls operations of subclass.
    69. Strategy Pattern Intent / Applicability
      • Intent
        • Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
      • Applicability – Use Strategy Pattern when…
        • Many related classes differ only in their behavior.
        • You need different variants of an algorithm. For example, defining different algorithms based on space-time tradeoffs.
        • An algorithm uses data that a client shouldn’t know about.
        • A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead, move related conditional branches into their own Strategy class.
    70. Strategy Pattern - Participants
      • Strategy
        • Declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.
      • ConcreteStrategy
        • Implements the algorithm using the Strategy interface.
      • Context
        • Is configured with a ConcreteStrategy object
        • Maintains a reference to a Strategy object
        • May define an interface that lets Strategy access its data.
    71. Strategy Pattern - Participants http://www.dofactory.com/Patterns/PatternStrategy.aspx Show code in RealWorld Example
      • Strategy
        • SortStrategy
      • ConcreteStrategy
        • QuickSort
        • ShellSort
        • MergeSort
      • Context
        • SortedList
      Picture & Example from: http:// www.dofactory.com/Patterns/PatternStrategy.aspx
    72. Strategy – Consequences
      • Good Consequences
        • Good for families of related algorithms. Inheritance can help factor out common functionality of algorithms.
        • Alternative to subclassing which allows the developer to vary the algorithm independent of its context.
        • Strategies eliminate conditional statements.
        • Provide different implementations of the same behavior. Example: Sorting is goal, but many ways to sort.
      • Drawbacks
        • Clients must be aware of different strategies.
        • Communication overhead between Strategy and Context – some concrete strategies may not need all the parameters passed into them.
        • Increased number of objects. See Flyweight pattern for an approach to solve this.
    73. Iterator
      • Intent
        • Provide a means to Iterate through a series of nodes in specific way(s)
      • Motivation
        • To traverse lists of information without having to know anything too specific about the objects
        • To implement multiple algorithms to traverse those nodes.
    74. Class Diagram
    75. Iterator:Implementation
      • Who Controls the Iteration?
        • External Iterator
          • Client controls iteration
          • Client must explicitly request next() on each node
        • Internal Iterator
          • Iterator controls iteration
          • Client hands an operation to the Iterator, Iterator tells every child in the aggregate to perform it.
    76. Implementation Benefits
      • External Iterator
        • More flexible than Internal. Can compare 2 collections easily
      • Internal Iterator
        • Easier to use, as they define the iteration logic for you. Makes portability easier.
    77. Who defines the traversal Algorithm?
      • Algorithm can be held by a class outside of the Iterator. It could be held by the aggregate can hold it.
        • Called “the cursor.”
        • Allows the algorithm to access private members of the aggregate (and not break encapsulation)
      • Algorithm is held by the iterator
        • Allows algorithms to be swapped out easily.
    78. How Robust is the Iterator?
      • If an iterator is robust it
        • Will allow for removal of nodes in the middle of traversal.
        • It does this through registering the iterator with the aggregate. If any nodes are removed, it is notified.
    79. Additional Iterator Operations
      • All come with first, next, isdone, and currentItem
      • Previous
        • Goes to the previous node that was iterated
        • Can be helpful in certain situations
      • SkipTo
        • Skips to a certain node.
        • Goes to a node matching specific criteria
    80. Observer Pattern
      • Behavioral Pattern
      • one-to-many dependency model, so that when one object changes state, all its dependents are notified and updated automatically without coupling the notifying object to the objects that are notified.
      Example:
      • Button expose a clicked event that encapsulate click state, thus publish himself as an observable. Clients that are interested in this event register to it, thus becomes observers.
      • Observer and observable are bonded in a contract and can be completely loosely coupled from one another.
    81. Singleton design pattern
      • Creational pattern
      • ensure that a class has only one instance, and to provide a global point of access to it
      Example: Class SomeClass { static SomeClass singleTonInstance = null; static SomeClass GetInstance() { if(singleTonInstance == null) singleTonInstance = new SomeClass() return singleTonInstance; } }
    82. Factory design patterns (Abstract Lightweight)
      • Creational pattern
      • Can be given to client (abstract), pass construction parameters or read creation types from configuration or system environment
      • Can use object pool (Lightweight)
    83. Factory design pattern - example abstract class GUIFactory { public static GUIFactory getFactory() { int sys = readFromConfigFile("OS_TYPE"); return sys == 0 ? new WinFactory() : new OSXFactory(); } public abstract Button createButton(); } class WinFactory:GUIFactory { public override Button createButton() { return new WinButton(); } } class MacFactory:GUIFactory { public override Button createButton(){ return new MacButton(); } } abstract class Button { public string caption; public abstract void paint(); }
    84. class WinButton:Button { public override void paint() { // paint a button with Win API…} } class MacButton:Button { public override void paint() { // paint a button Mac style… } } class Application { static void Main(string[] args) { GUIFactory aFactory = GUIFactory.getFactory(); Button aButton = aFactory.createButton(); aButton.caption = "Play"; aButton.paint(); } } Factory design pattern - example
    85. Façade design pattern
      • Structural Pattern
      • Provide a unified interface to a set of interfaces in a subsystem without damaging the genric form of the sub system.
    86. Decorator pattern
      • Structural Pattern
      • Avoid excessive sub-classing and gain run time flexibility
      • Example:
      Java.IO package BufferedReader br =  new  BufferedReader( new  InputStreamReader(            new  FileInputStream(inFile))); All derives from abstract io.Reader
    87. Example
    88. Example // the Window interface interface Window { public void draw(); // draws the Window public String getDescription(); // returns a description of the Window } // implementation of a simple Window without any scrollbars class SimpleWindow implements Window { public void draw() { // draw window } public String getDescription() { return "simple window"; } } // abstract decorator class - note that it implements Window abstract class WindowDecorator implements Window { protected Window decoratedWindow; // the Window being decorated public WindowDecorator (Window decoratedWindow) { this.decoratedWindow = decoratedWindow; } }
    89. Example // the first concrete decorator which adds vertical scrollbar functionality class VerticalScrollBarDecorator extends WindowDecorator { public VerticalScrollBarDecorator (Window decoratedWindow) { super(decoratedWindow); } public void draw() { drawVerticalScrollBar(); decoratedWindow.draw(); } private void drawVerticalScrollBar() { // draw the vertical scrollbar } public String getDescription() { return decoratedWindow.getDescription() + ", including vertical scrollbars"; } } // the second concrete decorator which adds horizontal scrollbar functionality class HorizontalScrollBarDecorator extends WindowDecorator { public HorizontalScrollBarDecorator (Window decoratedWindow) { super(decoratedWindow); } public void draw() { drawHorizontalScrollBar(); decoratedWindow.draw(); } private void drawHorizontalScrollBar() { // draw the horizontal scrollbar } public String getDescription() { return decoratedWindow.getDescription() + ", including horizontal scrollbars"; } }
    90. Example public class DecoratedWindowTest { public static void main(String[] args) { // create a decorated Window with // horizontal and vertical scrollbars Window decoratedWindow = new HorizontalScrollBarDecorator ( new VerticalScrollBarDecorator( new SimpleWindow())); // print the Window's description System.out.println(decoratedWindow.getDescription()); } } Output: "simple window, including vertical scrollbars, including horizontal scrollbars"
    91. Strategy Pattern
      • Behavioral Pattern
      • defines a family of interchangeable encapsulated algorithms that receives the same input type and provides the same output type in different manners that can be determined in run-time.
      static void Main( { SortedList studentRecords = new SortedList(); studentRecords.Add("Samual"); studentRecords.Add("Jimmy"); studentRecords.Add("Sandra");      studentRecords.SetSortStrategy(new QuickSort()); studentRecords.Sort(); studentRecords.SetSortStrategy(new ShellSort()); studentRecords.Sort();   }
    92. Strategy Pattern - example abstract class SortStrategy { public abstract void Sort(ArrayList list) } class QuickSort : SortStrategy { public override void Sort(ArrayList list) {       list.Sort(); // Default is Quicksort        } } class ShellSort : SortStrategy { public override void Sort(ArrayList list) {       //list.ShellSort(); not-implemented       }   }
    93. class SortedList { private ArrayList list = new ArrayList(); private SortStrategy sortstrategy; public void SetSortStrategy(SortStrategy sortstrategy) {       this.sortstrategy = sortstrategy; } public void Add(string name) {       list.Add(name); }      public void Sort() {      sortstrategy.Sort(list);    } } Strategy Pattern - example
    94. Proxy Pattern
      • Intent
        • Provide a surrogate or placeholder for another object to control access to it
      • Other Names
        • Surrogate
    95. Proxy Pattern: Applicability
      • Forms of the proxy pattern:
        • Remote proxy – Provides a local representative for an object in a different address space.
        • Virtual Proxy – Creates expensive objects on demand.
        • Protection Proxy – Controls access to the original object.
        • Smart References – Additional functionality pointers.
          • Smart Pointers
          • Initial loading of persistent objects.
          • Object locking.
    96. Proxy Pattern: Participants
      • Proxy
        • Maintains a reference to the real subject.
        • Provide identical interface to Subject so the Proxy can be substituted.
        • Controls access to the real subject and may be responsible for creating and deleting the real subject.
      • RealSubject
        • Defines the real object that the proxy represents.
      • Subject
        • Defines the common interface for RealSubject and Proxy so that the proxy to be used wherever a RealSubject is expected.
    97. Proxy Pattern: Structure
    98. Proxy Pattern: Example class Image; class ImagePtr { public: ImagePtr(const char* file); virtual ~ImagePtr(); virtual Image* operator->(); virtual Image& operator*(); private: Image* _image; const char* _file; Image* LoadImage(); }; Image* ImagePtr::LoadImage(){ If (_image == 0 ) { _image = LoadAnImageFile(_file); } return _image; } Image* ImagePtr::operator->() { return LoadImage(); } Image& ImagePtr::operator*(){ return *LoadImage(); } To implement the Real Subject methods: ImagePtr image = ImagePtr(“aFile”); image->Draw(Point(50,100)); //(image.operator->())->Draw(Point(50,100))
    99. Proxy Pattern: Consequences
      • Each proxy introduces a level of indirection. This may result in hiding detail from the implementer.
        • A remote Proxy can hide the fact that object resides in a different address space.
        • A Virtual Proxy can perform optimizations such as creation on demand.
        • Protection Proxy and Smart References can allow additional housekeeping tasks when object is accessed.
      • Copy-On-Write
        • This hides optimization in which an object is not copied until it’s attributes are modified.
    100. Proxy: Related Patterns
      • Adapter
        • Provides a different interface to an object. Since a proxy may deny request based on access, the interface is will be a subset.
      • Decorator
        • Similar implementation to proxy but has a different purpose. This adds responsibilities to an object rather than controlling access.
    101. Adapter Pattern
      • a.k.a. Wrapper
      • Has both class and object forms
      • Adapts the interface of one class into that of an otherwise incompatible class
      • Use to:
        • make use of a class with incompatible interface
        • create reusable class that will play nice with others
        • use several subclasses without having to subclass each one to adapt their interface (object form)
    102. Adapter Pattern
      • Structure
    103. Adapter Pattern
      • Participants
        • Target
          • defines the domain-specific interface that Client uses
        • Client
          • collaborates with objects conforming to Target interface
        • Adaptee
          • defines existing interface that needs adapting
        • Adapter
          • adapts the interface of Adaptee to the Target interface
      • Collaborations
        • Clients call operations on Adapter instance, which in turn calls the appropriate Adaptee operations
    104. Adapter Pattern
      • Consequences
        • Class form
          • commits to a concrete Adaptee class, so won’t work if we want to adapt a class as well as subclasses (use object form)
          • Adapter can override Adaptee’s behavior
          • introduces only one object; no pointer indirection required
        • Object form
          • allows single Adapter to work with many Adaptee subclasses; can add functionality to all Adaptees at once
          • harder to override Adaptee behvarior – have to subclass Adaptee and make Adapter refer to the subclass
    105. Adapter Pattern
      • Other Issues
        • How much work does Adapter do?
          • simple: changing names of otherwise identical operations
          • complex: supporting new functionality
        • Pluggable Adapters
          • use interface adaptation to make class more reusable
        • Two-way Adapters
          • a class adapter conforms to both incompatible classes
          • use multiple inheritance
    106. Adapter Pattern
      • Implementation Issues
        • Class adapters in C++
          • adapts publicly from Target and privately from Adaptee
          • Adapter is subtype of Target, not Adaptee
        • Pluggable Adapters
          • Find “narrow” interface – smallest subset of operations
          • Either:
            • make operations abstract in Target for different Adapters to implement
            • put operations in abstract delegate class for different Adapters to subclass
    107. Adapter Pattern
      • Related Patterns
        • Bridge – similar structure, but meant to separate interface from its implementation, rather than change interface of existing object
        • Decorator – enhances object without changing its interface. Thus more transparent and supports recursive composition
        • Proxy – defines surrogate for another object without changing its interface
    108. Bridge Pattern
      • a.k.a. Handle/Body
      • Decouples abstraction from its implementation
      • Use to:
        • avoid binding abstraction to implementation (i.e. want to choose different implementations at runtime)
        • make both abstraction and implementations independently extensible
        • change implementation or abstraction without impacting clients, or hide them from clients
        • share implementation among clients without letting them know
    109. Bridge Pattern
      • Structure:
    110. Bridge Pattern
      • Participants
        • Abstraction
          • defines abstraction’s interface
          • maintains reference to Implementor instance
        • RefinedAbstraction
          • extends interface defined by Abstraction
        • Implementor
          • defines interface for implementation classes
          • typically provides more primitive operations than Abstraction
        • ConcreteImplementor
          • implements Implementor interface
      • Collaborations
        • Abstraction forwards client requests to its Implementor object
    111. Bridge Pattern
      • Consequences
        • decouples interface and implementation
          • allows selecting implementation at runtime
          • avoids compilation dependencies on implementation
        • improves extensibility
          • Abstraction and Implementation can be extended independently
        • hides implementation details from clients
    112. Bridge Pattern
      • Implementation Issues
        • for only one implementation, may not need abstract Implementor
        • how, where, and when to choose concrete Implementor?
          • by Abstraction, in its constructor?
          • change at runtime?
          • by another object, like an Abstract Factory?
        • sharing Implementors
          • Handle/Body idiom
        • multiple inheritance
          • combines interface back with implementation
    113. Bridge Pattern
      • Related Patterns
        • Abstract Factory can create and configure Bridges
        • Adapter makes existing unrelated classes work together; whereas Bridge is used in design in effort to avoid needing Adapters later
    114. Consumer/Producer
      • Concurrency Pattern
      • This design pattern coordinates the concurrent production and consumption of information among producer and consumer objects that are working on different threads.
      • This pattern is used with some type of semaphore
    115. Consumer/Producer - example static AutoResetEvent eventProducerDone = new AutoResetEvent(false); static AutoResetEvent eventConsumerDone = new AutoResetEvent(false); static int currentNum = 0; static void produce(object stateInfo) { eventProducerDone.Set(); while (true) { //wait for the consumer eventConsumerDone.WaitOne(); currentNum++; eventProducerDone.Set(); } }
    116. static void Main(string[] args) { ThreadPool.QueueUserWorkItem(new WaitCallback(produce)); for (int i = 0; i < 20; i++) { eventProducerDone.WaitOne(); System.Diagnostics.Debug.WriteLine(currentNum); eventConsumerDone.Set(); } } Consumer/Producer - example
    117. Top 10 Misconceptions
      • (1) A pattern is a solution to a problem in a context.
      • Why isn’t this true?
        • Patterns are applied to recurring problems (not one instance).
        • Patterns teach , so that the developer can tailor the solution to a variant of the problem.
        • Patterns have a name .
    118. Top 10 Misconceptions
      • (2) Patterns are just jargon, rules, programming tricks, data structures, etc.
        • The idea of patterns is old… experienced programmers used previous solutions on new problems.
        • What is new is naming them and writing them down.
        • One drawback (from personal experience) is to assume everyone knows the pattern. Design documentation should note the name of the design pattern used, but that shouldn’t be the extent of the documentation.
    119. Top 10 Misconceptions
      • (3) Seen one, seen them all.
        • Patterns are extremely diverse.
        • Don’t make assumptions about all patterns based on a few patterns.
    120. Top 10 Misconceptions
      • (4) Patterns need tool or methodological support to be effective.
        • Benefits of patterns (no tool or support needed!)
          • Patterns capture expertise and make it accessible to non-experts.
          • Pattern names form a vocabulary which helps developers communicate.
          • Documenting the design with the patterns in use helps people understand the system more quickly.
          • Patterns facilitate restructuring a system whether or not it was designed with patterns in mind.
    121. Top 10 Misconceptions
      • (5) Patterns guarantee reusable software, higher productivity, world peace, etc.
        • Patterns don’t guarantee anything.
        • Similar comments were made about object-oriented programming when it was introduced.
      • (6) Patterns ‘generate’ whole architectures.
        • Need human creativity to know how to apply and tailor a pattern for your given problem.
        • Need to fill in the “white space” between the patterns.
        • Through teaching / discussion, patterns may support “generativity” – helping the reader solve problems that the pattern doesn’t address explicitly.
    122. Top 10 Misconceptions
      • (7) Patterns are for (object-oriented) design or implementation.
        • Patterns capture expertise, but are not limited to design and implementation.
        • Patterns can be found in analysis, maintenance, testing, documentation, organizational structure, etc.
    123. Top 10 Misconceptions
      • (8) There’s no evidence that patterns help anybody.
        • Improve teaching and communication.
      • (9) The pattern community is a clique of elites.
        • Attendees of Pattern Languages of Programming (PLoP) conferences included analysts, designers, implementors, students, professionals, authors, even a non-computer scientist.
      • (10) The pattern community is self-serving, even conspiratorial.
        • Common desire of leading pattern authors is to impart expertise, best practices, and competitive advantage to others.
    124. Thank You... [email_address]

    + Sudarsun SanthiappanSudarsun Santhiappan, 3 weeks ago

    custom

    115 views, 0 favs, 0 embeds more stats

    Introducing Software Architecture and Design Patter more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 115
      • 115 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 0
    • Downloads 11
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories