Wrapper Facade

Total Page:16

File Type:pdf, Size:1020Kb

Wrapper Facade Wrapper Facade A Structural Pattern for Encapsulating Functions within Classes Douglas C. Schmidt [email protected] Department of Computer Science Washington University St. Louis, MO 63130, (314) 935-7538 This paper appeared in the C++ Report magazine, Febru- ary, 1999. CLIENT DATABASE 1 Introduction PRINTER CONNECTION This paper describes the Wrapper Facade pattern. The intent REQUEST LOGGING of this pattern is to encapsulate low-level functions and data SERVER structures with object-oriented (OO) class interfaces. Com- SOCKET HANDLES mon examples of the Wrapper Facade pattern are class li- NETWORK braries like MFC, ACE, and AWT that encapsulate native CONSOLE OS C APIs, such as sockets, pthreads, or GUI functions. CLIENT LOGGING Programming directly to native OS C APIs makes net- RECORDS LOGGING working applications verbose, non-robust, non-portable, and RECORDS hard to maintain because it exposes many low-level, error- CLIENT SERVER prone details to application developers. This paper illus- trates how the Wrapper Facade pattern can help to make these types of applications more concise, robust, portable, and maintainable. Figure 1: Distributed Logging Service This paper is organized as follows: Section 2 describes the Wrapper Facade pattern in detail using the Siemens for- mat [1] and Section 3 presents concluding remarks. The logging server shown in Figure 1 handles connec- tion requests and logging records sent by clients. Logging records and connection requests can arrive concurrently on 2 Wrapper Facade Pattern multiple socket handles. Each handle identifies network communication resources managed within an OS. 2.1 Intent Clients communicate with the logging server using a connection-oriented protocol like TCP [2]. Thus, when a Encapsulate low-level functions and data structures within client wants to log data, it must first send a connection re- more concise, robust, portable, and maintainable higher- quest to the logging server. The server accepts connection level object-oriented class interfaces. requests using a handle factory, which listens on a network address known to clients. When a connection request ar- 2.2 Example rives, the OS handle factory accepts the client’s connection and creates a socket handle that represents this client’s con- To illustrate the Wrapper Facade pattern, consider the server nection endpoint. This handle is returned to the logging for a distributed logging service shown in Figure 1. Client server, which waits for client logging requests to arrive on applications use the logging service to record information this and other socket handles. Once clients are connected, about their execution status in a distributed environment. they can send logging records to the server. The server re- This status information commonly includes error notifica- ceives these records via the connected socket handles, pro- tions, debugging traces, and performance diagnostics. Log- cesses the records, and writes them to their output device(s). ging records are sent to a central logging server, which writes A common way to develop a logging server that processes the records to various output devices, such as a network man- multiple clients concurrently is to use low-level C language agement console, a printer, or a database. functions and data structures for threading, synchronization 1 and network communication. For instance, Figure 2 illus- // Set up the address to become a server. trates the use of Solaris threads [3] and the socket [4] net- memset (reinterpret_cast <void *> (&sock_addr), work programming API to develop a multi-threaded logging 0, sizeof sock_addr); server. sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons (logging_port); sock_addr.sin_addr.s_addr = htonl (INADDR_ANY); // Associate address with endpoint. SERVER LOGGING SERVER bind (acceptor, reinterpret_cast <struct sockaddr *> (&sock_addr), sizeof sock_addr); 1: socket() 2: bind() // Make endpoint listen for connections. 3: listen() listen (acceptor, 5); 8: recv() 8: recv() 5: accept() 9: write() 9: write() 6: thr_create() // Main server event loop. for (;;) { Logging Logging Logging thread_t t_id; Acceptor Handler Handler // Handle UNIX/Win32 portability differences. 4: connect() #if defined (_WINSOCKAPI_) 7: send() SOCKET h; #else 7: send() int h; CLIENT CLIENT #endif /* _WINSOCKAPI_ */ A NETWORK B // Block waiting for clients to connect. int h = accept (acceptor, 0, 0); // Spawn a new thread that runs the // <logging_handler> entry point and Figure 2: Multi-threaded Logging Server // processes client logging records on // socket handle <h>. thr_create (0, 0, In this design, the logging server’s handle factory accepts logging_handler, client network connections in its main thread. It then spawns reinterpret_cast <void *> (h), THR_DETACHED, a new thread that runs a logging handler function to &t_id); process logging records from each client in a separate con- } nection. The following two C functions illustrates how to /* NOTREACHED */ implement this logging server design using the native Solaris return 0; OS APIs for sockets, mutexes, and threads.1 } // At file scope. The logging handler function runs in a separate thread of control, i.e., one thread per connected client. It receives // Keep track of number of logging requests. static int request_count; and processes logging records on each connection, as fol- lows: // Lock to protect request_count. static mutex_t lock; // Entry point that processes logging records for // one client connection. // Forward declaration. void *logging_handler (void *arg) static void *logging_handler (void *); { // Handle UNIX/Win32 portability differences. // Port number to listen on for requests. #if defined (_WINSOCKAPI_) static const int logging_port = 10000; SOCKET h = reinterpret_cast <SOCKET> (arg); #else // Main driver function for the multi-threaded int h = reinterpret_cast <int> (arg); // logging server. Some error handling has been #endif /* _WINSOCKAPI_ */ // omitted to save space in the example. for (;;) { int UINT_32 len; // Ensure a 32-bit quantity. main (int argc, char *argv[]) char log_record[LOG_RECORD_MAX]; { struct sockaddr_in sock_addr; // The first <recv> reads the length // (stored as a 32-bit integer) of // Handle UNIX/Win32 portability differences. // adjacent logging record. This code #if defined (_WINSOCKAPI_) // does not handle "short-<recv>s". SOCKET acceptor; ssize_t n = recv #else (h, int acceptor; reinterpret_cast <char *> (&len), #endif /* _WINSOCKAPI_ */ sizeof len, 0); // Create a local endpoint of communication. // Bail out if we don’t get the expected len. if (n <= sizeof len) break; acceptor = socket (PF_INET, SOCK_STREAM, 0); len = ntohl (len); // Convert byte-ordering. if (len > LOG_RECORD_MAX) break; 1 Readers who are not interested in the complete code details of this ex- ample can skip to the pattern’s Context in Section 2.3. // The second <recv> then reads <len> 2 // bytes to obtain the actual record. across different versions of the same OS or compiler. Non- // This code handles "short-<recv>s". for (size_t nread = 0; portability stems from the lack of information hiding in low- nread < len; level APIs based on functions and data structures. nread += n) { For instance, the logging server implementation in Sec- n = recv (h, log_record + nread, tion 2.2 has hard-coded dependencies on several non- len - nread, 0); portable native OS threading and network programming C // Bail out if an error occurs. if (n <= 0) APIs. In particular, the use of thr create, mutex lock, return 0; and mutex unlock is not portable to non-Solaris OS plat- } forms. Likewise, certain socket features, such as the use of mutex_lock (&lock); int to represent a socket handle, are not portable to non- // Execute following two statements in a UNIX platforms like WinSock on Win32, which represent a // critical section to avoid race conditions socket handle as a pointer. // and scrambled output, respectively. ++request_count; // Count # of requests received. High maintenance effort: C and C++ developers typically if (write (1, log_record, len) == -1) achieve portability by explicitly adding conditional com- // Unexpected error occurred, bail out. pilation directives into their application source code using break; #ifdefs. However, using conditional compilation to ad- mutex_unlock (&lock); dress platform-specific variations at all points of use in- } creases the physical design complexity [6] of application close (h); source code. It is hard to maintain and extend such software return 0; since platform-specific implementation details are scattered } throughout the application source files. Note how all the threading, synchronization, and networking For instance, the #ifdefs that handle Win32 and UNIX code is programmed using the low-level C functions and data portability with respect to the data type of a socket, i.e., structures provided by the Solaris operating system. SOCKET vs. int, impedes the readability of the code. Developers who program to low-level C APIs like these 2.3 Context must have intimate knowledge of many OS platform idiosyn- crasies to write and maintain this code. Applications that access services provided by low-level func- As a result of these drawbacks, developing applications by tions and data structures. programming directly to low-level functions and data struc- tures is rarely an effective design choice for application soft- 2.4 Problem ware. Networking applications are often written using the low- level functions and data structures illustrated in Section 2.2. 2.5
Recommended publications
  • 1. Domain Modeling
    Software design pattern seminar sse, ustc Topic 8 Observer, Mediator, Facade Group K 1. The observer pattern (Behavioral pattern, chapter 16 and 17) 1) the observer is an interface or abstract class defining the operations to be used to update itself 2) a solution to these problems A. Decouple change and related responses so that such dependencies can be added or removed freely and dynamically 3) solution A. Observable defines the operations for attaching, de-attaching and notifying observers B. Observer defines the operations to update itself 4) liabilities A. Unwanted concurrent update to a concrete observable may occur Figure 1 Sample Observer Pattern 2. The mediator pattern (Behavioral pattern, chapter 16 and 17) 1) the mediator encapsulates how a set of objects interact and keeps objects from referring to each other explicitly 2) a solution to these problems A. a set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand B. reusing an object is difficult because it refers to and communicates with many other objects C. a behavior that's distributed between several classes should be customizable without a lot of subclassing 3) solution A. Mediator defines an interface for communicating with Colleague objects, knows the colleague classes and keep a reference to the colleague objects, and implements the communication and transfer the messages between the colleague classes 1 Software design pattern seminar sse, ustc B. Colleague classes keep a reference to its Mediator object, and communicates with the Mediator whenever it would have otherwise communicated with another Colleague 4) liabilities A.
    [Show full text]
  • Automatic Verification of Java Design Patterns
    Automatic Verification of Java Design Patterns Alex Blewitt, Alan Bundy, Ian Stark Division of Informatics, University of Edinburgh 80 South Bridge, Edinburgh EH1 1HN, UK [email protected] [email protected] [email protected] Abstract 2. Design patterns There are a number of books which catalogue and de- Design patterns are widely used by object oriented de- scribe design patterns [4, 1, 6] including an informal de- signers and developers for building complex systems in ob- scription of the key features and examples of their use. ject oriented programming languages such as Java. How- However, at the moment there are no books which attempt ever, systems evolve over time, increasing the chance that to formalise these descriptions, possibly for the following the pattern in its original form will be broken. reasons: We attempt to show that many patterns (implemented in Java) can be verified automatically. Patterns are defined 1. The implementation (and description) of the pattern is in terms of variants, mini-patterns, and constraints in a language-specific. pattern description language called SPINE. These specifi- 2. There are often several ways to implement a pattern cations are then processed by HEDGEHOG, an automated within the same language. proof tool that attempts to prove that Java source code 3. Formal language descriptions are not common within meets these specifications. the object oriented development community. Instead, each pattern is presented as a brief description, and an example of its implementation and use. Designers and developers are then expected to learn the ‘feel’ of a pat- 1.
    [Show full text]
  • Addison Wesley, 2000, Pp
    ------==Proudly Presented by MODELER==------ preface.fm Page xv Wednesday, June 6, 2001 4:18 PM Preface Design patterns and object-oriented programming. They hold such promise to make your life as a software designer and developer eas- ier. Their terminology is bandied about every day in the technical and even the popular press. But it can be hard to learn them, to become proficient with them, to understand what is really going on. Perhaps you have been using an object-oriented or object-based language for years. Have you learned that the true power of objects is not inheritance but is in “encapsulating behaviors”? Perhaps you are curious about design patterns and have found the literature a bit too esoteric and high-falutin. If so, this book is for you. It is based on years of teaching this material to software developers, both experienced and new to object orientation. It is based upon the belief—and our experience—that once you understand the basic principles and motivations that underlie these concepts, why they are doing what they do, your learning curve will be incredibly shorter. And in our discussion of design patterns, you will under- stand the true mindset of object orientation, which is a necessity before you can become proficient. As you read this book, you will gain a solid understanding of the ten most essential design patterns. You will learn that design pat- terns do not exist on their own, but are supposed to work in con- cert with other design patterns to help you create more robust applications.
    [Show full text]
  • Object-Oriented Analysis, Design and Implementation
    Undergraduate Topics in Computer Science Brahma Dathan Sarnath Ramnath Object-Oriented Analysis, Design and Implementation An Integrated Approach Second Edition Undergraduate Topics in Computer Science Undergraduate Topics in Computer Science (UTiCS) delivers high-quality instruc- tional content for undergraduates studying in all areas of computing and information science. From core foundational and theoretical material to final-year topics and applications, UTiCS books take a fresh, concise, and modern approach and are ideal for self-study or for a one- or two-semester course. The texts are all authored by established experts in their fields, reviewed by an international advisory board, and contain numerous examples and problems. Many include fully worked solutions. More information about this series at http://www.springer.com/series/7592 Brahma Dathan • Sarnath Ramnath Object-Oriented Analysis, Design and Implementation An Integrated Approach Second Edition 123 Brahma Dathan Sarnath Ramnath Department of Information and Computer Department of Computer Science Science and Information Technology Metropolitan State University St. Cloud State University St. Paul, MN St. Cloud, MN USA USA Series editor Ian Mackie Advisory Board Samson Abramsky, University of Oxford, Oxford, UK Karin Breitman, Pontifical Catholic University of Rio de Janeiro, Rio de Janeiro, Brazil Chris Hankin, Imperial College London, London, UK Dexter Kozen, Cornell University, Ithaca, USA Andrew Pitts, University of Cambridge, Cambridge, UK Hanne Riis Nielson, Technical University of Denmark, Kongens Lyngby, Denmark Steven Skiena, Stony Brook University, Stony Brook, USA Iain Stewart, University of Durham, Durham, UK A co-publication with the Universities Press (India) Private Ltd., licensed for sale in all countries outside of India, Pakistan, Bhutan, Bangladesh, Sri Lanka, Nepal, The Maldives, Middle East, Malaysia, Indonesia and Singapore.
    [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]
  • (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]
  • Designpatternsphp Documentation Release 1.0
    DesignPatternsPHP Documentation Release 1.0 Dominik Liebler and contributors Jul 18, 2021 Contents 1 Patterns 3 1.1 Creational................................................3 1.1.1 Abstract Factory........................................3 1.1.2 Builder.............................................8 1.1.3 Factory Method......................................... 13 1.1.4 Pool............................................... 18 1.1.5 Prototype............................................ 21 1.1.6 Simple Factory......................................... 24 1.1.7 Singleton............................................ 26 1.1.8 Static Factory.......................................... 28 1.2 Structural................................................. 30 1.2.1 Adapter / Wrapper....................................... 31 1.2.2 Bridge.............................................. 35 1.2.3 Composite............................................ 39 1.2.4 Data Mapper.......................................... 42 1.2.5 Decorator............................................ 46 1.2.6 Dependency Injection...................................... 50 1.2.7 Facade.............................................. 53 1.2.8 Fluent Interface......................................... 56 1.2.9 Flyweight............................................ 59 1.2.10 Proxy.............................................. 62 1.2.11 Registry............................................. 66 1.3 Behavioral................................................ 69 1.3.1 Chain Of Responsibilities...................................
    [Show full text]
  • Principles of Programming Languages
    David Liu Principles of Programming Languages Lecture Notes for CSC324 (Version 2.1) Department of Computer Science University of Toronto principles of programming languages 3 Many thanks to Alexander Biggs, Peter Chen, Rohan Das, Ozan Erdem, Itai David Hass, Hengwei Guo, Kasra Kyanzadeh, Jasmin Lantos, Jason Mai, Sina Rezaeizadeh, Ian Stewart-Binks, Ivan Topolcic, Anthony Vandikas, Lisa Zhang, and many anonymous students for their helpful comments and error-spotting in earlier versions of these notes. Dan Zingaro made substantial contributions to this version of the notes. Contents Prelude: The Study of Programming Languages 7 Programs and programming languages 7 Models of computation 11 A paradigm shift in you 14 Course overview 15 1 Functional Programming: Theory and Practice 17 The baseline: “universal” built-ins 18 Function expressions 18 Function application 19 Function purity 21 Name bindings 22 Lists and structural recursion 26 Pattern-matching 28 Higher-order functions 35 Programming with abstract syntax trees 42 Undefined programs and evaluation order 44 Lexical closures 50 Summary 56 6 david liu 2 Macros, Objects, and Backtracking 57 Object-oriented programming: a re-introduction 58 Pattern-based macros 61 Objects revisited 74 The problem of self 78 Manipulating control flow I: streams 83 Manipulating control flow II: the ambiguous operator -< 87 Continuations 90 Using continuations in -< 93 Using choices as subexpressions 94 Branching choices 98 Towards declarative programming 101 3 Type systems 109 Describing type systems 110
    [Show full text]
  • TH`ESE DE DOCTORAT Software Engineering Techniques For
    THESE` DE DOCTORAT de L’UNIVERSITE´ DE NICE – SOPHIA ANTIPOLIS Sp´ecialit´e SYSTEMES` INFORMATIQUES pr´esent´ee par Matthias Jung pour obtenir le grade de DOCTEUR de l’UNIVERSITE´ DE NICE – SOPHIA ANTIPOLIS Sujet de la th`ese: Software Engineering Techniques for Support of Communication Protocol Implementation Soutenu le 3 Octobre 2000 devant le jury compos´e de: Pr´esident Dr. Walid Dabbous Directeur de Recherche, INRIA Rapporteurs Dr. Wolfgang Effelsberg Professeur, Universit´e de Mannheim Dr. B´eatrice Paillassa Maˆıtre de Conf´erence, ENSEEIHT Membre Invit´e Dr. Vincent Roca Charg´e de Recherche, INRIA Directeur de Th`ese Dr. Ernst W. Biersack Professeur, Institut Eur´ecom ii Acknowledgements Thanks to my supervisor Ernst Biersack for his trust and his honesty, his encouragement, and the many things I’ve learned during the last three years. Thanks to Stefan B¨ocking and the people from Siemens Research (ZT IK2) for their financial support, which gave me the opportunity to follow my PhD studies at Eur´ecom. Thanks to the members of my jury – Walid Dabbous, Wolfgang Effelsberg, B´eatrice Paillassa, and Vincent Roca – for the time they spent to read and comment my work. Thanks to Didier Loisel and David Tr´emouillac for their permanent cooperation and competent help concerning hardware and software administration. Thanks to Evelyne Biersack, Morsy Cheikhrouhou, Pierre Conti, and Yves Roudier for reading and correcting the french part of my dissertation. Thanks to the btroup members and to all people at Eur´ecom who contributed to this unique atmosphere of amity and inspiration. Thanks to Sergio for his open ear and for never running out of cookies.
    [Show full text]
  • Design Patterns in Ocaml
    Design Patterns in OCaml Antonio Vicente [email protected] Earl Wagner [email protected] Abstract The GOF Design Patterns book is an important piece of any professional programmer's library. These patterns are generally considered to be an indication of good design and development practices. By giving an implementation of these patterns in OCaml we expected to better understand the importance of OCaml's advanced language features and provide other developers with an implementation of these familiar concepts in order to reduce the effort required to learn this language. As in the case of Smalltalk and Scheme+GLOS, OCaml's higher order features allows for simple elegant implementation of some of the patterns while others were much harder due to the OCaml's restrictive type system. 1 Contents 1 Background and Motivation 3 2 Results and Evaluation 3 3 Lessons Learned and Conclusions 4 4 Creational Patterns 5 4.1 Abstract Factory . 5 4.2 Builder . 6 4.3 Factory Method . 6 4.4 Prototype . 7 4.5 Singleton . 8 5 Structural Patterns 8 5.1 Adapter . 8 5.2 Bridge . 8 5.3 Composite . 8 5.4 Decorator . 9 5.5 Facade . 10 5.6 Flyweight . 10 5.7 Proxy . 10 6 Behavior Patterns 11 6.1 Chain of Responsibility . 11 6.2 Command . 12 6.3 Interpreter . 13 6.4 Iterator . 13 6.5 Mediator . 13 6.6 Memento . 13 6.7 Observer . 13 6.8 State . 14 6.9 Strategy . 15 6.10 Template Method . 15 6.11 Visitor . 15 7 References 18 2 1 Background and Motivation Throughout this course we have seen many examples of methodologies and tools that can be used to reduce the burden of working in a software project.
    [Show full text]
  • Resilience Design Patterns a Structured Approach to Resilience at Extreme Scale - Version 1.0
    ORNL/TM-2016/687 Resilience Design Patterns A Structured Approach to Resilience at Extreme Scale - version 1.0 Saurabh Hukerikar Christian Engelmann Approved for public release. October 2016 Distribution is unlimited. DOCUMENT AVAILABILITY Reports produced after January 1, 1996, are generally available free via US Department of Energy (DOE) SciTech Connect. Website: http://www.osti.gov/scitech/ Reports produced before January 1, 1996, may be purchased by members of the public from the following source: National Technical Information Service 5285 Port Royal Road Springfield, VA 22161 Telephone: 703-605-6000 (1-800-553-6847) TDD: 703-487-4639 Fax: 703-605-6900 E-mail: [email protected] Website: http://classic.ntis.gov/ Reports are available to DOE employees, DOE contractors, Energy Technology Data Ex- change representatives, and International Nuclear Information System representatives from the following source: Office of Scientific and Technical Information PO Box 62 Oak Ridge, TN 37831 Telephone: 865-576-8401 Fax: 865-576-5728 E-mail: [email protected] Website: http://www.osti.gov/contact.html This report was prepared as an account of work sponsored by an agency of the United States Government. Neither the United States Government nor any agency thereof, nor any of their employees, makes any warranty, express or implied, or assumes any legal lia- bility or responsibility for the accuracy, completeness, or usefulness of any information, apparatus, product, or process disclosed, or rep- resents that its use would not infringe privately owned rights. Refer- ence herein to any specific commercial product, process, or service by trade name, trademark, manufacturer, or otherwise, does not nec- essarily constitute or imply its endorsement, recommendation, or fa- voring by the United States Government or any agency thereof.
    [Show full text]
  • Design Pattern- Structural Pattern 2015
    Design Pattern- Structural pattern 2015 Adapter Intent: Change the interface of a class into another interface which is expected by the client. Also Know As: Wrapper Motivation Structure (Class) Structure (Object) Applicability • Use an existing class whose interface does not match the requirement • Create a reusable class though the interfaces are not necessary compatible with callers • Want to use several existing subclasses, but it is impractical to subclass everyone. (Object Adapter Only) Participants Target (Shape) 1 | P a g e Almas Ansari Design Pattern- Structural pattern 2015 defines the domain-specific interface that Client uses. Client (DrawingEditor) collaborates with objects conforming to the Target interface. Adaptee (TextView) defines an existing interface that needs adapting. Adapter (TextShape) adapts the interface of Adaptee to the Target interface. Collaborations Clients call operations on an Adapter instance. In turn, the adapter calls Adaptee operations that carry out the request. Consequences Here are other issues to consider when using the Adapter pattern: 1. How much adapting does Adapter do? Adapters vary in the amount of work they do to adapt Adaptee to the Target interface. 2. Pluggable adapters. A class is more reusable when you minimize the assumptions other classes must make to use it. 3. Using two-way adapters to provide transparency. A potential problem with adapters is that they aren't transparent to all clients. Implementation 1. Implementing class adapters in C++. In a C++ implementation of a class adapter, Adapter would inherit publicly from Target and privately from Adaptee. Thus Adapter would be a subtype of Target but not of Adaptee. 2.
    [Show full text]