Design Patterns

Total Page:16

File Type:pdf, Size:1020Kb

Design Patterns Design patterns OOD Lecture 6 Next lecture • Monday, Oct 1, at 1:15 pm, in 1311 • Remember that the poster sessions are in two days – Thursday, Sep 27 • 1:15 or 3:15 pm (check which with your TA) • Room 2244 + 2245 The object design activity Select sub-system Specification Re-use Specifying types & signatures Specifying visibility Identifying missing attributes & operations Identifying components Adjusting components Specifying constraints Specifying exceptions Adjusting patterns Identifying patterns Check use cases Restructuring Optimization Revisiting inheritanc Optimizing access paths Collapsing classes Caching complex computations Realizing associations Delaying complex computations What are design patterns? • Software problems generally have more than one solution: How do you choose which to use? – Patterns give guidance in the form of solution types based on experience • Patterns are also communication tools: “I’m using pattern X” instead of lengthy descriptions of solution details. Communication abstraction • Design patterns are not designs — only helpful hints Pattern elements • A name • Description of a typical problem • The elements that make up the pattern: Classes, relations, responsibilities, collaborations • Consequences: Pros, cons, trade-offs • An example solution The concept of design patterns • Nothing new in itself. Patterns are to a large degree verbalized and externalized experience, no matter what your discipline • The “Gang of Four book” (GoF) started people thinking more in these terms for s/w design – Gamma, Erich, Richard Helm, Ralph Johnson, John Vlissides (1995) Design Patterns: Elements of Reusable Object-Oriented Software. Addison- Wesley. ISBN 978-0-2016-3361-0 • Inspired by architectural theory: Christopher Alexander (1977) A Pattern Language: Towns, Buildings, Construction “Classic” patterns • Creational patterns – Abstract factory, Builder, Factory method, Singleton, Prototype • Structural patterns – Adapter, Bridge, Composite, Decorator, Façade, Flyweight, Proxy • Behavioural patterns – Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template method, Visitor Factory method Creational pattern • Problem – Hard-coding class names in code makes code less flexible • Damages re-use, changes might require multiple consistent updates – Testing: E.g. stubbing production data – Shielding user from complex creation, possibly involving data the user shouldn’t have access to • Solution – Decouple creation point from class name – Use separate method for instance creation – Encapsulates the places needing changes – Multiple pluggable creators with common interface Factory method UML «interface» Creator +factoryMethod() : Product Product ConcreteCreator +factoryMethod() : Product • DIP + OCP (+ ISP + LSP), decoupling • Dependency injection (technique for achieving dependency inversion) • Dependency defined by Creator • Injector/Provider/Container = ConcreteCreator • Dependent = whatever uses Product Factory method: Before class Bonniers { void publish(String title, String author, String text) { … String isbn = kb.lookup(title, author); Book b = new ISBNBook(title, author, isbn); … } } public class ISBNBook { public ISBNBook(String title, String author, String isbn) { … } … } Factory method: After public interface BookCreator { Book makeBook(String title, String author); } «interface» Creator public class BooksWithISBN implements BookCreator { @override +factoryMethod() : Product Book makeBook(String title, String author) { String isbn = kb.lookup(title, author); return new ISBNBook(title, author, isbn); } } // different package class Bonniers { BookCreatorProdu bc;ct ConcreteCreator void publish(String title, String author, String text) { ... +factoryMethod() : Product Book b = bc.makeBook(title, author); ... } } Factory method Other uses • Also used to encapsulate object creation when it’s complex or it’s convenient to delay decision class ImageReaderFactory { static ImageReader getImageReader(InputStream is) { switch(determineImageType(is)) { case ImageReaderFactory.GIF: return new GifReader(is); case ImageReaderFactory.JPEG: return new JpegReader(is); // … } } } Factory method Limitations • Introducing factory methods might break existing clients • Reduces coupling by increasing complexity Abstract factory pattern • Generalization of factory method pattern «interface» «uses» Client AbstractFactory +createProductA() : AbstractProductA +createProductB() : AbstractProductB «uses» «interface» AbstractProductA ConcreteFactory1 «instantiates» ProductA1 ProductA2 +createProductA() : ProductA1 +createProductB() : ProductB1 «instantiates» ConcreteFactory2 «uses» +createProductA() : ProductA2 «interface» +createProductB() : ProductB2 AbstractProductB «instantiates» ProductB1 ProductB2 «instantiates» Composite Structural pattern • Description: Represent a hierarchy of variable width and depth so that leaves and composites can be uniformly accessed through a common interface • Examples – Syntax trees for arithmetical expressions (such as (((x+2)*y)+3)*(z+1)) – Organizational chart – In general, anything that can be seen as tree structured Composite Example Domain object Solution object • Instance diagram Add x + (y * 2) x Multiply y 2 Composite Solution Structure Participants • Component – Provides the common interface Component * – May provide interface to both parent parent and children (e.g. evaluate for arithmetic expressions) • Composite Leaf Composite leaves – Primitive with children – Implements behaviour for 1 composite objects • Leaf – Primitive w/out children Navigability – uni- or bidirectional – not part of – Implements behaviour for the pattern terminal objects Composite Example in code interface Expression { int evaluate(Map<String, int> environment); } class Add implements Expression { private Expression lhs; private Expression rhs; public Add(Expression l, Expression r) { lhs = l; rhs = r; } public int evaluate(Map<String, int> environment) { return lhs.evaluate(environment) + rhs.evaluate(environment); } } C o m p o n e n t * class Integer implements Expression { private int value; p a r e n t public Integer(int v) { value = v; } public int evaluate(Map<String, int> _env) { return value; } } l e a v e s class Variable implements Expression { L e a f C o m p o s i t e private String name; 1 public Variable(String n) { name = n; } public int evaluate(Map<String, int> env) { return environment.get(name); } } Composite Consequences and issues • Pro – Simplifies the client – Easy to add new kinds of components (e.g. division) • Contra – Recursive composition of objects • Behaviour depends on composition • Issues – How to provide access to children? • In Component (Expression) or in Composite (Add etc) • Pseudo-problem – Explicit parent references? – Sharing components? – Child ordering? Proxy Structural pattern • Expose only a subset of an object interface to clients • Improve the performance or the security of a system by delaying expensive computations, using memory only when needed, or checking access before loading an object into memory Proxy Solution Structure Participants • Subject Subject Client attribute1 – The interface that clients see attribute2 operation1() • RealObject operation2() – Class with expensive computations or security RealObject ProxyObject attribute1 issues attribute1 attribute2 attribute2 moreAttributes • operation1() 1 0..1 operation1() ProxyObject operation2() operation2() moreOperations() – Acts on behalf of RealObject until the expensive computation is needed, when it delegates to the real object Proxy Consequences • Pro: The Client is shielded from any optimizations for handling RealObjects • Contra: Adds a level of indirection between Client and RealObject (i.e. increases complexity) Proxy Example in code interface AlgebraServer { int calculate(Expression expression); } class RemoteServer implements AlgebraServer{ int calculate(ExpressionSubject expression) { ... } Client } attribute1 attribute2 operation1() class CachingProxy implementsoperation2() AlgebraServer { HashMap<Expression, Value> cache = new HashMap<Expression, Value>(); RemoteServer server; int calculate(Expression expression) { RealObject int result; ProxyObject attribute1 attribute1 attribute2 if (cache.hasKey(expression))attribute2 moreAt tr{ib utes resultope r=at iocache.get(expression);n1() 1 0..1 operation1() operation2() operation2() } else { moreOperations() result = server.calculate(expression); cache.put(expression, new Value(result)); } return result; } } Strategy Behavioural pattern • Decouple a policy-deciding class from a set of mechanisms so that different mechanisms can be changed transparently from a client Strategy pattern Library example • University library lending policies – Normal book, no outstanding requests: • Undergraduate borrower: 2 weeks • Everyone else: 4 weeks – Normal book, outstanding request: 1 week – Reference book: Cannot be borrowed – New book: 1 week – Reserved book: 3 days Strategy pattern Library example: Implementation #1 int getLoanLength(Book b, Patron p) { if (p.isReserved()) { return 3; } if (b.isNormalBook()) { if (p.hasOutstandingRequest()) { return 7;} if (p.isUnderGraduate()) { return 14; } else { return 28; } } if(p.isNewBook()) { return 7; } return 0; // is reference book } • Logic implementation in single method – Inflexible, as logic is hard-coded – Results in ugly code that is hard to read Strategy pattern Library example: Design #2 Book -loanLength : unsigned short(idl) +getLoanLength() : unsigned
Recommended publications
  • 1 Design Pattern for Open Class (DRAFT) 2 Abstract Factory
    1 Design Pattern for Open Class (DRAFT) Tanaka Akira <[email protected]> A design pattern describes a software architecture which is reusable and exten- sible. [GoF] is the book containing 23 design patterns for OOP languages like C++ and Java. [GoF] describes several trade offs of the patterns. In C++ and Java, a class is defined by only one module. However, there are languages which can define a class by two or more modules: Cecil, MultiJava, AspectJ, MixJuice, CLOS, Ruby, etc. Such class is called "open class" because it is extensible by modules implemented later [Chambers]. For languages with open class, more extensible and/or simpler design patterns exists. We studied design patterns with open class for each GoF design patterns. In this paper, we describe two patterns: the Abstract Factory pattern and the Visitor pattern. 2 Abstract Factory The Abstract Factory pattern is a design pattern for separating class names from the code which generates the object group of related classes for making them configurable. Following figure is the class diagram of the Abstract Factory pattern. Since the example described in [GoF] uses only one concrete factory for each binaries, the required concrete factory is selected statically. The example builds two binaries for Motif and Presentation Manager from a single source code. Two concrete factories are exist for Motif and Presentation Manager. When a binary is built, it is selected which concrete factory is linked. Such static selection can be implemented with the fewer number of classes by open class as following modules. • The module which defines Window and ScrollBar class and their methods which is independent to window systems.
    [Show full text]
  • Acceptor-Connector an Object Creational Pattern for Connecting and Initializing Communication Services
    Acceptor-Connector An Object Creational Pattern for Connecting and Initializing Communication Services Douglas C. Schmidt [email protected] Department of Computer Science Washington University St. Louis, MO 63130, USA An earlier version of this paper appeared in a chapter in TRACKING the book Pattern Languages of Program Design 3, edited SATELLITES STATION by Robert Martin, Frank Buschmann, and Dirke Riehle pub- PEERS lished by Addison-Wesley, 1997. 1Intent STATUS INFO The Acceptor-Connector design pattern decouples connec- WIDE AREA NETWORK tion establishment and service initialization in a distributed COMMANDS BULK DATA system from the processing performed once a service is ini- TRANSFER tialized. This decoupling is achieved with three compo- nents: acceptors, connectors,andservice handlers. A con- GATEWAY nector actively establishes a connection with a remote ac- ceptor component and initializes a service handler to pro- cess data exchanged on the connection. Likewise, an ac- LOCAL AREA NETWORK ceptor passively waits for connection requests from remote GROUND connectors, establishing a connection upon arrival of such a STATION PEERS request, and initializing a service handler to process data ex- changed on the connection. The initialized service handlers Figure 1: The Physical Architecture of a Connection- then perform application-specific processing and communi- oriented Application-level Gateway cate via the connection established by the connector and ac- ceptor components. The Gateway transmits data between its Peers using the connection-oriented TCP/IP protocol [1]. In our exam- 2 Example ple network configuration, each service is bound to a con- nection endpoint designated by an IP host address and a TCP To illustrate the Acceptor-Connector pattern, consider the port number.
    [Show full text]
  • Design Patterns Promote Reuse
    Design Patterns Promote Reuse “A pattern describes a problem that occurs often, along with a tried solution to the problem” - Christopher Alexander, 1977 • Christopher Alexander’s 253 (civil) architectural patterns range from the creation of cities (2. distribution of towns) to particular building problems (232. roof cap) • A pattern language is an organized way of tackling an architectural problem using patterns Kinds of Patterns in Software • Architectural (“macroscale”) patterns • Model-view-controller • Pipe & Filter (e.g. compiler, Unix pipeline) • Event-based (e.g. interactive game) • Layering (e.g. SaaS technology stack) • Computation patterns • Fast Fourier transform • Structured & unstructured grids • Dense linear algebra • Sparse linear algebra • GoF (Gang of Four) Patterns: structural, creational, behavior The Gang of Four (GoF) • 23 structural design patterns • description of communicating objects & classes • captures common (and successful) solution to a category of related problem instances • can be customized to solve a specific (new) problem in that category • Pattern ≠ • individual classes or libraries (list, hash, ...) • full design—more like a blueprint for a design The GoF Pattern Zoo 1. Factory 13. Observer 14. Mediator 2. Abstract factory 15. Chain of responsibility 3. Builder Creation 16. Command 4. Prototype 17. Interpreter 18. Iterator 5. Singleton/Null obj 19. Memento (memoization) 6. Adapter Behavioral 20. State 21. Strategy 7. Composite 22. Template 8. Proxy 23. Visitor Structural 9. Bridge 10. Flyweight 11.
    [Show full text]
  • Design Pattern Interview Questions
    DDEESSIIGGNN PPAATTTTEERRNN -- IINNTTEERRVVIIEEWW QQUUEESSTTIIOONNSS http://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm Copyright © tutorialspoint.com Dear readers, these Design Pattern Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Design Pattern. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: What are Design Patterns? Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time. What is Gang of Four GOF? In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development. These authors are collectively known as Gang of Four GOF. Name types of Design Patterns? Design patterns can be classified in three categories: Creational, Structural and Behavioral patterns. Creational Patterns - These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new opreator. This gives program more flexibility in deciding which objects need to be created for a given use case. Structural Patterns - These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.
    [Show full text]
  • Tree Visitors in Clojure Update the Java Visitor Pattern with Functional Zippers
    Tree visitors in Clojure Update the Java Visitor pattern with functional zippers Skill Level: Intermediate Alex Miller ([email protected]) Senior Engineer Revelytix 20 Sep 2011 JVM language explorer Alex Miller has recently discovered the benefits of implementing the Visitor pattern using Clojure, a functional Lisp variant for the Java Virtual Machine. In this article, he revisits the Visitor pattern, first demonstrating its use in traversing tree data in Java programs, then rewriting it with the addition of Clojure's functional zippers. I’ve used trees of domain objects in my Java applications for many years. More recently, I’ve been using them in Clojure. In each case, I've found that the Visitor pattern is a reliable tool for manipulating trees of data. But there are differences in how the pattern works in a functional versus object-oriented language, and in the results it yields. About Clojure Clojure is a dynamic and functional programming language variant of Lisp, written specifically for the JVM. Learn more about Clojure on developerWorks: •"The Clojure programming language" •"Clojure and concurrency" •"Solving the Expression Problem with Clojure 1.2" •"Using CouchDB with Clojure" In this article, I revisit domain trees and the Visitor pattern for the Java language, Tree visitors in Clojure Trademarks © Copyright IBM Corporation 2011 Page 1 of 27 developerWorks® ibm.com/developerWorks then walk through several visitor implementations using Clojure. Being a functional language, Clojure brings new tricks to data query and manipulation. In particular, I've found that integrating functional zippers into the Visitor pattern yields efficiency benefits, which I explore.
    [Show full text]
  • Learning Javascript Design Patterns
    Learning JavaScript Design Patterns Addy Osmani Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo Learning JavaScript Design Patterns by Addy Osmani Copyright © 2012 Addy Osmani. All rights reserved. Revision History for the : 2012-05-01 Early release revision 1 See http://oreilly.com/catalog/errata.csp?isbn=9781449331818 for release details. ISBN: 978-1-449-33181-8 1335906805 Table of Contents Preface ..................................................................... ix 1. Introduction ........................................................... 1 2. What is a Pattern? ...................................................... 3 We already use patterns everyday 4 3. 'Pattern'-ity Testing, Proto-Patterns & The Rule Of Three ...................... 7 4. The Structure Of A Design Pattern ......................................... 9 5. Writing Design Patterns ................................................. 11 6. Anti-Patterns ......................................................... 13 7. Categories Of Design Pattern ............................................ 15 Creational Design Patterns 15 Structural Design Patterns 16 Behavioral Design Patterns 16 8. Design Pattern Categorization ........................................... 17 A brief note on classes 17 9. JavaScript Design Patterns .............................................. 21 The Creational Pattern 22 The Constructor Pattern 23 Basic Constructors 23 Constructors With Prototypes 24 The Singleton Pattern 24 The Module Pattern 27 iii Modules 27 Object Literals 27 The Module Pattern
    [Show full text]
  • Automating Testing with Autofixture, Xunit.Net & Specflow
    Design Patterns Michael Heitland Oct 2015 Creational Patterns • Abstract Factory • Builder • Factory Method • Object Pool* • Prototype • Simple Factory* • Singleton (* this pattern got added later by others) Structural Patterns ● Adapter ● Bridge ● Composite ● Decorator ● Facade ● Flyweight ● Proxy Behavioural Patterns 1 ● Chain of Responsibility ● Command ● Interpreter ● Iterator ● Mediator ● Memento Behavioural Patterns 2 ● Null Object * ● Observer ● State ● Strategy ● Template Method ● Visitor Initial Acronym Concept Single responsibility principle: A class should have only a single responsibility (i.e. only one potential change in the S SRP software's specification should be able to affect the specification of the class) Open/closed principle: “Software entities … should be open O OCP for extension, but closed for modification.” Liskov substitution principle: “Objects in a program should be L LSP replaceable with instances of their subtypes without altering the correctness of that program.” See also design by contract. Interface segregation principle: “Many client-specific I ISP interfaces are better than one general-purpose interface.”[8] Dependency inversion principle: One should “Depend upon D DIP Abstractions. Do not depend upon concretions.”[8] Creational Patterns Simple Factory* Encapsulating object creation. Clients will use object interfaces. Abstract Factory Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Inject the factory into the object. Dependency Inversion Principle Depend upon abstractions. Do not depend upon concrete classes. Our high-level components should not depend on our low-level components; rather, they should both depend on abstractions. Builder Separate the construction of a complex object from its implementation so that the two can vary independently. The same construction process can create different representations.
    [Show full text]
  • Dependency Injection in Unity3d
    Dependency Injection in Unity3D Niko Parviainen Bachelor’s thesis March 2017 Technology, communication and transport Degree Programme in Software Engineering Description Author(s) Type of publication Date Parviainen, Niko Bachelor’s thesis March 2017 Language of publication: English Number of pages Permission for web publi- 57 cation: x Title of publication Dependency Injection in Unity3D Degree programme Degree Programme in Software Engineering Supervisor(s) Rantala, Ari Hämäläinen, Raija Assigned by Psyon Games Oy Abstract The objective was to find out how software design patterns and principles are applied to game development to achieve modular design. The tasks of the research were to identify the dependency management problem of a modular design, find out what the solutions offered by Unity3D are, find out what the dependency injection pattern is and how it is used in Unity3D environment. Dependency management in Unity3D and the dependency injection pattern were studied. Problems created by Unity3D’s solutions were introduced with examples. Dependency in- jection pattern was introduced with examples and demonstrated by implementing an ex- ample game using one of the available third-party frameworks. The aim of the example game was to clarify if the use of dependency injection brings modularity in Unity3D envi- ronment and what the cost of using it is. The principles of SOLID were introduced with generic examples and used to assist depend- ency injection to further increase the modularity by bringing the focus on class design. Dependency injection with the help of SOLID principles increased the modularity by loosely coupling classes even though slightly increasing the overall complexity of the architecture.
    [Show full text]
  • Facet: a Pattern for Dynamic Interfaces
    Facet: A pattern for dynamic interfaces Author: Eric Crahen SUNY at Buffalo CSE Department Amherst, NY 14260 201 Bell Hall 716-645-3180 <[email protected]> Context: Wherever it is desirable to create a context sensitive interface in order to modify or control the apparent behavior if an object. Problem: How can I modify the behavior of an existing object so that different behaviors are shown under different circumstances; and yet still maintain a clean separation between the policy (when each behavior is available) and implementation of each behavior allowing them to be developed independently of one another? Forces: Interfaces provide an essential level of abstraction to object oriented programming. Generally, objects are able define aspects of their function very well using interfaces. At times, this may not be enough. When dealing with two or more classes whose responsibilities are distinctly separate, but whose behavior is closely related, classes can begin to resist modularization. For example, adding security to an application means inserting code that performs security checks into numerous locations in existing classes. Clearly, these responsibilities are distinct; the original classes being responsible for the tasks they were designed to perform, and the security classes being responsible for providing access control. However, making those original classes secure means intermingling code that deals with security. When the classes dealing with security are changed many classes are going to be impacted. One method of adding new behavior to an existing class might be to simply create a subclass and embed that new behavior. In the security example, this would mean creating a subclass for each class that needs to be secure and adding calls to the security code.
    [Show full text]
  • (MVC) Design Pattern Untuk Aplikasi Perangkat Bergerak Berbasis Java
    View metadata, citation and similar papers at core.ac.uk brought to you by CORE provided by Diponegoro University Institutional Repository Model-View-Controller (MVC) Design Pattern Untuk Aplikasi Perangkat Bergerak Berbasis Java Panji Wisnu Wirawan Program Studi Teknik Informatika, Universitas Diponegoro [email protected] Abstrak Design pattern merupakan salah satu teknik mendesain komponen perangkat lunak yang bisa digunakan kembali. MVC design pattern merupakan design pattern untuk komponen perangkat lunak yang memisahkan secara tegas antara model data, tampilan, dan kendali perangkat lunak. Artikel ini akan membahas MVC design pattern disertai kesesuaiannya dengan aplikasi perangkat bergerak berbasis Java. Bagian akhir artikel ini menunjukkan bagaimana MVC design pattern untuk aplikasi bergerak berbasis Java. Kata Kunci : MVC, design pattern , aplikasi perangkat bergerak berbasis Java ulang sehingga dapat meminimalkan usaha 1. Pendahuluan pengembangan aplikasi perangkat bergerak. Pada umumnya, aplikasi perangkat bergerak menggunakan Komponen perangkat lunak sudah semestinya GUI. Penggunaan MVC diharapkan bermanfaat untuk didesain dan diimplementasikan sehingga bisa pembuatan komponen perangkat lunak untuk aplikasi digunakan ulang ( reused ) pada perangkat lunak yang bergerak yang bisa digunakan ulang. [6] lain . Sebagai contoh penggunaan komponen perangkat lunak yang dapat digunakan ulang adalah Salah satu penelitian mengenai design pattern penggunaan text box , drop down menu dan untuk aplikasi perangkat bergerak berbasis Java telah sebagainya. dilakukan oleh Narsoo dan Mohamudally (2008). Narsoo dan Mohamudally (2008) melakukan Contoh lain dari komponen perangkat lunak identifikasi design pattern untuk mobile services adalah pola-pola tertentu untuk menyelesaikan menggunakan Java 2 Mobile Edition (J2ME). Mobile masalah yang disebut sebagai design pattern . Pola- services tersebut termasuk dalam behavioral pattern pola tersebut akan tetap sama untuk aplikasi yang yaitu add , edit , erase dan search .
    [Show full text]
  • Object-Oriented Desgin Visitor Pattern George Blankenship 1
    Object-Oriented Desgin Visitor Pattern CSCI 253 Object Oriented Design: Visitor Pattern George Blankenship Visitor Pattern George Blankenship 1 Overview Creational Patterns Structural Patterns Behavioral Patterns Singleton Composite Chain of Respons. Abstract factory Façade Command Factory Method Proxy Interpreter Prototype Flyweight Iterator Builder Mediator Adapter Memento Bridge Observer Decorator State Strategy Template Method Visitor Pattern George Blankenship Visitor 2 The Elements of a Design Pattern • A pattern name • The problem that the pattern solves – Including conditions for the pattern to be applicable • The solution to the problem brought by the pattern – The elements (classes-objects) involved, their roles, responsibilities, relationships and collaborations – Not a particular concrete design or implementation • The consequences of applying the pattern – Time and space trade off – Language and implementation issues – Effects on flexibility, extensibility, portability Visitor Pattern George Blankenship 3 George Blankenship 1 Object-Oriented Desgin Visitor Pattern The Visitor Pattern: The Problem Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates • many distinct and unrelated operations need to be performed on objects in an object structure an you want to avoid “polluting” their classes with these operations • the classes defining the object structure rarely change but you often want to define new operations over the structure Visitor Pattern George Blankenship 4 Visitor Example • The root of the structure accepts a visitor: root.accept( visitor ) • The root and every child object in the structure have a an accept method: void accept( visitor ) { visitor.visit( this ); for each child of mine child.accept( visitor ) next } • In short order our visitor gets a visit() call from each object in the collection.
    [Show full text]
  • Dependency Injection with Unity
    D EPEN DEPENDENCY INJECTION WITH UNITY Over the years software systems have evolutionarily become more and more patterns & practices D ENCY complex. One of the techniques for dealing with this inherent complexity Proven practices for predictable results of software systems is dependency injection – a design pattern that I allows the removal of hard-coded dependencies and makes it possible to Save time and reduce risk on your NJECT assemble a service by changing dependencies easily, whether at run-time software development projects by or compile-time. It promotes code reuse and loosely-coupled design which incorporating patterns & practices, I leads to more easily maintainable and flexible code. Microsoft’s applied engineering ON guidance that includes both production The guide you are holding in your hands is a primer on using dependency quality source code and documentation. W I injection with Unity – a lightweight extensible dependency injection TH DEPENDENCY INJECTION container built by the Microsoft patterns & practices team. It covers The guidance is designed to help U software development teams: various styles of dependency injection and also additional capabilities N I of Unity container, such as object lifetime management, interception, Make critical design and technology TY and registration by convention. It also discusses the advanced topics of selection decisions by highlighting WITH UNITY enhancing Unity with your custom extensions. the appropriate solution architectures, technologies, and Microsoft products The guide contains plenty of trade-off discussions and tips and tricks for for common scenarios managing your application cross-cutting concerns and making the most out of both dependency injection and Unity. These are accompanied by a Understand the most important Dominic Betts real world example that will help you master the techniques.
    [Show full text]