Observer Pattern Visitor Pattern

Total Page:16

File Type:pdf, Size:1020Kb

Observer Pattern Visitor Pattern OBSERVER PATTERN Das Observer Pattern gehört zu den Behavioural Patterns. Es dient zur Weitergabe von Änderungen an einem Objekt an davon abhängige Strukturen. Das Pattern besteht aus einem Publisher und einem oder mehreren Subscribern (Observern). Der Publisher besitzt eine Liste von Subscribern die sein Event abonniert haben. Durch das attach Feature des Publishers wird ein Subscriber in die Liste eingefügt. Mit detach wird ein Subscriber entfernt. Jedes Mal wenn ein Event eintritt geht der Publisher durch seine Subscriberliste und ruft auf jedem Subscriber "update" auf. Beispiel: Problemstellung: Auf Druck der Taste "p" soll das Programm "Demo" pausieren. Der Publisher "pub" erkennt dass "p" gedrückt wird, daraufhin geht er durch die Subscriberliste und ruft auf jedem Element "update" auf. "Demo" erbt von Subscriber und hat sich zuvor über "subscribe" / pub.attach in die Liste des Publishers eingetragen. Daher wird demo.update aufgerufen und "Demo" kann sich selber pausieren. Der Sinn von Subscriber.subscribe(...) ist uns nicht ganz klar, da dieses Feature nichts anderes macht als p.attach(...) aufzurufen. VISITOR PATTERN Problem: Assignment Attempts, um typabhängig eine bestimmte Funktion aufzurufen (Dynamic Binding). Solution: Visitor Pattern. Trennung von Daten- und Funktionsklassen. Datenklassen erben von VISITABLE, Funktionen von VISITOR. Visitor vs dynamic binding: Dynamic binding: + Typen hinzufügen einfach - Operationen hinzufügen schwierig - Verwandte Operationen werden getrennt (repair_binding in BOOK, repair_cover in DVD) Visitor: - Typen hinzufügen schwierig + Operationen hinzufügen einfach + Keine assignment attempts (besser für type checking) + Verwandte Operation bleiben in einer Klasse, nicht verwandte werden getrennt Example: Before: /maintain (b : BORROWABLE) is -- Perform maintenance on b. require exists: b /= Void local book : BOOK dvd : DVD do book ?= b if book /= Void then if book.binding_damaged then book.repair_binding end end dvd ?= b if dvd /= Void then if dvd.cover_damaged then dvd.repair_cover end end end end/ Analog für andere Operationen, z.B. display(b: BORROWABLE)... After: BOOK und DVD erben von VISITABLE und implementieren dessen deffered Feature accept* /class BOOK inherit BORROWABLE VISITABLE feature accept (v : VISITOR) is -- Apply to v the book -- visit mechanism. do v.visit_book (Current)??? end end/ Analog für DVD MAINTAINANCE_VISITOR erbt von VISITOR und implementiert dessen deffered Features visit_book*, visit_dvd*,... /class MAINTENANCE_VISITOR inherit VISITOR feature -- Basic operations visit_book (book: BOOK) is -- Perform maintenance operations on b. do if book.binding_damaged then book.repair_binding end end visit_dvd (dvd: DVD) is -- Perform maintenance operations on d. do if dvd.cover_damaged then dvd.repair_cover end end end / STRATEGY PATTERN Klassen Diagramm: Beschreibung: Die ConcreteStrategyA und ConcreteStrategyB Klassen sind von der Selben Algorithmen Familie. Sie berechnen ähnliche Probleme. Die Klasse Strategie definiert das Problem abstrakt, also ohne konkrete Implementierung Die Klasse Context benutzt die konkreten Klassen über STRATEGY via dynamic binding als Client zur Berechnung des Algorithmus. Meist wird die konkrete Strategie von aussen (ROOT_CLASS) dem CONTEXT zugewiesen. Beispiel Schachspiel: CONTEXT: der Spieler STRATEGY : seine Spielstrategie CONCRETE_STRATEGY_A: So schnell wie möglich die Dame schnappen CONCRETE_STRATEGY_B: So gut wie möglich den König verteidigen Vorteile Vermeidung von unübersichtlichen if-statements Erweiterbarkeit mit neuen Strategien ist einfacher (Keine Neuimplementierung von CONTEXT). Freie Wahl von verschiedenen Implementierungen Nachteile Viel mehr Objekte, viel mehr Klassen. Viel mehr Kommunikation zwischen den Objekten. Der Benutzer (ROOT_CLASS) muss die verschiedenen Strategien kennen. STATE PATTERN Das State Pattern ist dann nützlich, wenn man ein Programm hat, welches zwischen verschiedenen Zuständen wechselt (quasi eine finite state machine) und in jedem State jeweils ähliche aber nicht gleiche Funktionalitäten bieten soll. Es wird eine deferred Klasse STATE geschrieben, wo die gewünschten features ohne Implementation definiert sind. Die effektiven States erben dann davon und werden jeweils aktiv wenn sich das Programm in diesem State befindet. Durch dieses Pattern wird der Code übersichtlicher und erweiterbar: Es gibt keine grossen select Blöcke und man kann neue States einfach direkt als neue Klasse schreiben. Ein ausführliches Beispiel zum State Pattern findet ihr im ersten Foliensatz dieses Semesters (beim letzten, "guten" Ansatz für das Flugreservationsprogramm)! Es wird dort zwar nirgends gesagt, dass es sich um das State Pattern handelt, aber genau das ist der Fall. CHAIN OF RESPONSIBILITY PATTERN Ein Sender eines Requests für die Bearbeitung eines Jobs hat mehrere Objekte in einer Kette zur Verfügung, welche diesen Job bearbeiten können. • Falls ein Objekt den Job nicht bearbeiten kann, reicht er ihn weiter an das nächste Objekt in der Kette. • Falls das Objekt den Job bearbeiten kann, wird dies gemacht und dem Sender des Requests gemeldet. Chain of responsibility request PE PE PE PE PE PE Pe: Processing element/Handler • Architektur: next handle can_handle* APPLICATION HANDLER [G]* do_handle* handled set_next FIRST_HANDLER [G]+ SECOND_HANDLER can_handle+ [G]+ do_handle+ can_handle+ do_handle+ handle (r: G) is do if can_handle (r) then do_handle (r); handled := True; elseif next /= Void then next.handle (r); handled := next.handled; else handled := False end end Real World Example Firma hat Präsident, Vice-Präsident und Direktor. Chain: Direktor Æ Vice-Präsident Æ Präsident Æ VR • Falls jetzt ein Auftrag in der Höhe < 25000 Fr. kommt, bearbeitet das der Direktor. • Falls Auftrag < 50000 Fr. wird das vom Vize-Präsident entschieden. • Falls Auftrag < 100000 Fr. übernimmt das der Präsident, weil es bereits eine grosse Summe ist. • Falls Auftrag >= 100000 Fr. muss der gesamte Verwaltungsrat in einer Sitzung entscheiden, weil das eine so riesige Summe ist. COMMAND PATTERN Ziel Implementation von Undo/Redo Mechanismen (Ctrl Z / Ctrl Y). Realisierung Jeder umkehrbare („undoable“) Command wird als eigene Klasse implementiert. Diese Klasse erbt von einer Master-Command-Klasse. Sie muss die deferred features implementieren/enthalten. Die History ist eine FIFO Liste welche sämtliche Commands speichert. Masterklasse deferred class COMMAND feature done: BOOLEAN is -- Has this command been executed? execute is -- Carry out one execution of this command. deferred ensure already: done end undo is -- Cancel an earlier execution of this command. require already: done deferred end redo is -- Restores an earlier execution of this command. require not_already: not done deferred end end Ausführen eines Benutzerbefehls User Request decodieren Fall 1: Normaler Befehl – Command-Object wird erstellt und ausgeführt – in der History werden sämtliche Elemente gelöscht, welche das done-Flag nicht gesetzt haben (alle rechts der aktuellen Cursor-Position). Fall 2: Undo – Sofern an der aktuellen Cursor-Position ein Command existiert, wird dessen Undo Feature aufgerufen und die Cursor-Position um eins nach hinten verschoben. Fall 3: Redo – Sofern an der aktuellen Cursor-Position ein Command existiert, wird dessen Redo Feature aufgerufen und die Cursor-Position um eins nach vorne verschoben. Alternative Implementation Zu jedem Command wird eine Undo- und eine Redofunktion implementiert. Anstatt in der History den Comand zu speichern wird ein Tupel mit den Agents zu Undo und Redo erstellt. Nun werden nicht mehr Execute/Redo und Undo, sondern die entsprechenden Agents aufgerufen. ABSTRACT FACTORY PATTERN Problem Unterschiedliche Objekte vom gleichen Typ abhängig von (evt. „äusseren“) Bedingungen nötig. Klassisches Beispiel: Verschiedenen Buttons, Fenster etc. nötig, je nach Betriebssystem. Lösung Durch Abstract Factory: Eine Abstract Factory liefert ein Interface zur Erstellung von Objekten, ohne dass man deren dynamischen Typ kennen muss. Klassendiagramm: Klassenbeschreibungen: Factory: Deferred Class. Stellt ein generelles Interface für die Erstellung von Produkten dar. Listet die einzelnen Produkte als deferred Features: new_produkt_a (args): PRODUCT_A is deferred end new_produkt_b: PRODUCT_B is deferred end … PRODUCT_A und PRODUCT_B sind selbst ebenfalls deferred. Factory_1 / Factory_2: Erben von Factory und liefern unterschiedliche Implementationen der Instanzierung der einzelnen Produkte. new_produkt_a (args): PRODUCT_A is do create {PRODUCT_A1} Result.make (args) end oder: new_produkt_a (args): PRODUCT_A1 is do create Result.make (args) end Factory Objekt erstellen, Variante 1: feature -- Access factory: FACTORY feature --Something initialize is -- factory initialization do if some_condition then create {FACTORY_1} factory else create {FACTORY_2} factory end end Factory Objekt erstellen, Variante 2 mit Singleton (empfohlen) feature – Singleton factory: FACTORY is -- factory singleton once if some_condition then create {FACTORY_1} Result else create {FACTORY_2} Result end end Factory call my_product := factory.new_product_a SINGLETON PATTERN (Creational) Source: Gamma et al. (1994); also known as „Gang of Four“ (GoF); pages 127ff: Intent „Ensure a class only has one instance, and [to] provide a global point of access to it.“ Motivation and Applications Printer spooler, window manager, accounting system, calendar application, ... all applications that include some components that should only be created once, but will be used throughout the
Recommended publications
  • The Future of Embedded Software
    The Future of Embedded Software Edward A. Lee Professor, Chair of EE, and Associate Chair of EECS UC Berkeley ARTEMIS 2006 Annual Conference Graz, Austria May 22-24, 2006 Why Embedded Software? Why Now? “Information technology (IT) is on the verge of another revolution. Driven by the increasing capabilities and ever declining costs of computing and communications devices, IT is being embedded into a growing range of physical devices linked together through networks and will become ever more pervasive as the component technologies become smaller, faster, and cheaper... These networked systems of embedded computers ... have the potential to change radically the way people interact with their environment by linking together a range of devices and sensors that will allow information to be collected, shared, and processed in unprecedented ways. ... The use of [these embedded computers] throughout society could well dwarf previous milestones in the information revolution.” National Research Council Report Embedded Everywhere Lee, Berkeley 2 The Key Obstacle to Progress: Gap Between Systems and Computing | Traditional dynamic systems theory needs to adapt to better account for the behavior of software and networks. | Traditional computer science needs to adapt to embrace time, concurrency, and the continuum of physical processes. Lee, Berkeley 3 The Next Systems Theory: Simultaneously Physical and Computational The standard model: Embedded software is software on small computers. The technical problem is one of optimization (coping with limited resources). The Berkeley model: Embedded software is software integrated with physical processes. The technical problem is managing time and concurrency in computational systems. Lee, Berkeley 4 Obstacles in Today’s Technology: Consider Real Time Electronics Technology Delivers Timeliness… … and the overlaying software abstractions discard it.
    [Show full text]
  • Framework Overview with UML Diagrams
    Framework Overview with UML Diagrams Learn to Build Robust, Scalable and Maintainable Applications using PureMVC Framework Overview This document discusses the classes and interfaces of the PureMVC framework; illustrating their roles, responsibilities and collaborations with simple UML (Unified Modeling Language) diagrams. The PureMVC framework has a very narrow goal. That is to help you separate your application’s coding concerns into three discrete tiers; Model, View and Controller. In this implementation of the classic MVC design meta-pattern, the application tiers are represented by three Singletons (a class where only one instance may be created). A fourth Singleton, the Façade, simplifies development by providing a single interface for communications throughout the application. The Model caches named references to Proxies, which expose an API for manipulating the Data Model (including data retrieved from remote services). The View primarily caches named references to Mediators, which adapt and steward the View Components that make up the user interface. The Controller maintains named mappings to Command classes, which are stateless, and only created when needed. The Façade initializes and caches the Core actors (Model, View and Controller), and provides a single place to access all of their public methods. AUTHOR: Cliff Hall <[email protected]> LAST MODIFIED: 3/05/2008 Façade and Core The Façade class makes it possible for the Proxies, Mediators and Commands that make up most of our final application to talk to each other in a loosely coupled way, without having to import or work directly with the Core framework actors. When we create a concrete Façade implementation for our application, we are able to use the Core actors ‘out of the box’, incidental to our interaction with the Façade, minimizing the amount of API knowledge the developer needs to have to be successful with the framework.
    [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]
  • The Problem with Threads
    The Problem With Threads Edward A. Lee Robert S. Pepper Distinguished Professor and Chair of EECS UC Berkeley -and - Senior Technical Adviser, director, and co-founder of BDTI Class #: ESC-211 Embedded Systems Conference (ESC) Tuesday, 3 April 2007 Concurrency in Software Practice, As of 2007 | Component technologies z Objects in C++, C#, or Java z Wrappers as service definitions | Concurrency z Threads (shared memory, semaphores, mutexes, …) z Message Passing (synchronous or not, buffered, …) | Distributed computing z Distributed objects wrapped in web services, Soap, CORBA, DCOM, … Lee, Berkeley & BDTI 2 z1 Observations Threads and objects dominate SW engineering. z Threads: Sequential computation with shared memory. z Objects: Collections of state variables with procedures for observing and manipulating that state. Even distributed objects create the illusion of shared memory through proxies. z The components (objects) are (typically) not active. z Threads weave through objects in unstructured ways. z This is the source of many software problems. Lee, Berkeley & BDTI 3 The Buzz “Multicore architectures will (finally) bring parallel computing into the mainstream. To effectively exploit them, legions of programmers must emphasize concurrency.” The vendor push: “Please train your computer science students to do extensive multithreaded programming.” Lee, Berkeley & BDTI 4 z2 Is this a good idea? Lee, Berkeley & BDTI 5 My Claim Nontrivial software written with threads, semaphores, and mutexes are incomprehensible to humans. Lee, Berkeley & BDTI 6 z3 To Examine the Problems With Threads and Objects, Consider a Simple Example “The Observer pattern defines a one-to-many dependency between a subject object and any number of observer objects so that when the subject object changes state, all its observer objects are notified and updated automatically.” Design Patterns, Eric Gamma, Richard Helm, Ralph Johnson, John Vlissides (Addison-Wesley Publishing Co., 1995.
    [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]
  • Design Pattern Implementation in Java and Aspectj
    Design Pattern Implementation in Java and AspectJ Jan Hannemann Gregor Kiczales University of British Columbia University of British Columbia 201-2366 Main Mall 201-2366 Main Mall Vancouver B.C. V6T 1Z4 Vancouver B.C. V6T 1Z4 jan [at] cs.ubc.ca gregor [at] cs.ubc.ca ABSTRACT successor in the chain. The event handling mechanism crosscuts the Handlers. AspectJ implementations of the GoF design patterns show modularity improvements in 17 of 23 cases. These improvements When the GoF patterns were first identified, the sample are manifested in terms of better code locality, reusability, implementations were geared to the current state of the art in composability, and (un)pluggability. object-oriented languages. Other work [19, 22] has shown that implementation language affects pattern implementation, so it seems The degree of improvement in implementation modularity varies, natural to explore the effect of aspect-oriented programming with the greatest improvement coming when the pattern solution techniques [11] on the implementation of the GoF patterns. structure involves crosscutting of some form, including one object As an initial experiment we chose to develop and compare Java playing multiple roles, many objects playing one role, or an object [27] and AspectJ [25] implementations of the 23 GoF patterns. playing roles in multiple pattern instances. AspectJ is a seamless aspect-oriented extension to Java, which means that programming in AspectJ is effectively programming in Categories and Subject Descriptors Java plus aspects. D.2.11 [Software Engineering]: Software Architectures – By focusing on the GoF patterns, we are keeping the purpose, patterns, information hiding, and languages; D.3.3 intent, and applicability of 23 well-known patterns, and only allowing [Programming Languages]: Language Constructs and Features – the solution structure and solution implementation to change.
    [Show full text]
  • The Mvc-Web Design Pattern
    THE MVC-WEB DESIGN PATTERN Ralph F. Grove and Eray Ozkan Department of Computer Science, James Madison University, Harrisonburg, VA, U.S.A. Keywords: Web, Web framework, Design patterns, Model view controller pattern. Abstract: The Model-View-Controller design pattern is cited as the architectural basis for many web development frameworks. However, the version of MVC used for web development has changed as it has evolved from the original Smalltalk MVC. This paper presents an analysis of those changes, and proposes a separate Web-MVC pattern that more accurately describes how MVC is implemented in web frameworks. 1 INTRODUCTION 2 SMALLTALK MVC The Model-View-Controller (MVC) design pattern The MVC design pattern was introduced with the is cited as the basis for the architecture of several Smalltalk programming environment as a way to web application frameworks, such as ASP .Net, structure interactive applications in a modular Rails, and Struts. The MVC pattern was originally fashion (Krasner and Pope, 1988). As the name implemented in the Smalltalk-80 programming implies, the MVC design pattern decomposes environment developed at Xerox PARC (Goldberg functionality into three major components. and Robson, 1985). As it has been adapted for web The model component encapsulates the domain- frameworks the MVC pattern has evolved in specific structure and functionality of the different ways, resulting in implementations that application. This essentially includes the state of the differ significantly from each other and from the application and operations that can change state. The original Smalltalk implementation. model also maintains dependencies of view and The first goal of this paper is to present the MVC controller components, which it notifies in the event design pattern, both in its original form (section 2) of changes in state.
    [Show full text]
  • Java Design Patterns I
    Java Design Patterns i Java Design Patterns Java Design Patterns ii Contents 1 Introduction to Design Patterns 1 1.1 Introduction......................................................1 1.2 What are Design Patterns...............................................1 1.3 Why use them.....................................................2 1.4 How to select and use one...............................................2 1.5 Categorization of patterns...............................................3 1.5.1 Creational patterns..............................................3 1.5.2 Structural patterns..............................................3 1.5.3 Behavior patterns...............................................3 2 Adapter Design Pattern 5 2.1 Adapter Pattern....................................................5 2.2 An Adapter to rescue.................................................6 2.3 Solution to the problem................................................7 2.4 Class Adapter..................................................... 11 2.5 When to use Adapter Pattern............................................. 12 2.6 Download the Source Code.............................................. 12 3 Facade Design Pattern 13 3.1 Introduction...................................................... 13 3.2 What is the Facade Pattern.............................................. 13 3.3 Solution to the problem................................................ 14 3.4 Use of the Facade Pattern............................................... 16 3.5 Download the Source Code.............................................
    [Show full text]
  • Functional Programming at Work in Object-Oriented Programming
    Functional Programming at Work in Object-Oriented Programming Narbel version 2010 Narbel Functional Programming at Work in Object-Oriented Programming 1 A Claim about Programming Styles Claim: Adding functional programming capabilities to an object-oriented language leads to benefits in object-oriented programming design. Narbel Functional Programming at Work in Object-Oriented Programming 2 Existing Languages with a FP-OOP Mix Some old and less old languages with FP+OOP: For instance, Smalltalk, Common Lisp (CLOS). More recently, Python or Ruby. Notations: FP, Functional programming; OOP, Object-oriented programming, Narbel Functional Programming at Work in Object-Oriented Programming 3 FP techniques emulated in OOP Practices in OOP languages include emulations of FP techniques: C++ programmers: function pointers and overloadings of the () operator, i.e. “object-functions” or functors. Java programmers: anonymous classes and introspection/reflexion. Narbel Functional Programming at Work in Object-Oriented Programming 4 Existence of FP-OOP Comparison Points The idea of using FP to enrich OOP is old, see e.g. the discussions about the problem of the user-defined datatype extension: User-defined types and procedural data structures as complementary approaches to data abstraction. Reynolds. 1975. The Expression Problem. Wadler. 1998. Narbel Functional Programming at Work in Object-Oriented Programming 5 A Trend: FP Extensions for OO Languages A recent trend: to propose and include typed FP extensions in mainstream static OO languages. Extensions for C++ (see e.g. Laufer, Striegnitz, McNamara, Smaragdakis), and work in progress in the C++ standard committees. Java 7 expected to include FP constructs. C# offers FP constructs (even more in its 3.0 version).
    [Show full text]
  • Design Patterns Mock Test
    DDEESSIIGGNN PPAATTTTEERRNNSS MMOOCCKK TTEESSTT http://www.tutorialspoint.com Copyright © tutorialspoint.com This section presents you various set of Mock Tests related to Design Patterns Framework. You can download these sample mock tests at your local machine and solve offline at your convenience. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. DDEESSIIGGNN PPAATTTTEERRNNSS MMOOCCKK TTEESSTT IIII Q 1 - Which of the following describes the Composite pattern correctly? A - This pattern builds a complex object using simple objects and using a step by step approach. B - This pattern is used where we need to treat a group of objects in similar way as a single object. C - This pattern hides the complexities of the system and provides an interface to the client using which the client can access the system. D - This pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance. Q 2 - Which of the following describes the Decorator pattern correctly? A - This pattern allows a user to add new functionality to an existing object without altering its structure. B - This pattern is used where we need to treat a group of objects in similar way as a single object. C - This pattern hides the complexities of the system and provides an interface to the client using which the client can access the system. D - This pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance. Q 3 - Which of the following describes the Facade pattern correctly? A - This pattern allows a user to add new functionality to an existing object without altering its structure.
    [Show full text]
  • Developing GUI Applications. Architectural Patterns Revisited
    Developing GUI Applications: Architectural Patterns Revisited A Survey on MVC, HMVC, and PAC Patterns Alexandros Karagkasidis [email protected] Abstract. Developing large and complex GUI applications is a rather difficult task. Developers have to address various common soFtware engineering problems and GUI-speciFic issues. To help the developers, a number of patterns have been proposed by the software community. At the architecture and higher design level, the Model-View-Controller (with its variants) and the Presentation-Abstraction- Control are two well-known patterns, which specify the structure oF a GUI application. However, when applying these patterns in practice, problems arise, which are mostly addressed to an insuFFicient extent in the existing literature (iF at all). So, the developers have to find their own solutions. In this paper, we revisit the Model-View-Controller, Hierarchical Model-View- Controller, and Presentation-Abstraction-Control patterns. We first set up a general context in which these patterns are applied. We then identiFy Four typical problems that usually arise when developing GUI applications and discuss how they can be addressed by each of the patterns, based on our own experience and investigation oF the available literature. We hope that this paper will help GUI developers to address the identified issues, when applying these patterns. 1 Introduction Developing a large and complex graphical user interface (GUI) application for displaying, working with, and managing complex business data and processes is a rather difficult task. A common problem is tackling system complexity. For instance, one could really get lost in large number of visual components comprising the GUI, not to mention the need to handle user input or track all the relationships between the GUI and the business logic components.
    [Show full text]
  • Observer Pattern Using Aspect-Oriented Programming∗
    Observer Pattern using Aspect-Oriented Programming∗ Eduardo Kessler Piveta Laborat´oriode Banco de Dados e Engenharia de Software (LBDES) Centro Universit´arioLuterano de Palmas Universidade Luterana do Brasil 77054-970, Palmas, TO [email protected] Luiz Carlos Zancanella Laborat´oriode Seguran¸caem Computa¸c˜ao(LabSEC) Universidade Federal de Santa Catarina Campus Universit´ario 88040-900 Florian´opolis, SC [email protected] Abstract This paper discusses the representation and implementation of the Observer design pattern using aspect-oriented techniques. 1 Introduction Several object-oriented design techniques have been used to specify and implement design patterns efficiently. However there are several patterns that affect system modularity, where base objects are highly affected by the structures that the pattern requires. In other cases we want to apply a pattern to classes that already belong to a hierarchy. This could be hard depending on the pattern. ∗Copyright c 2003. Permission is granted to copy for the SugarloafPLoP 2003 Con- ference. All other rights are reserved. Observer Pattern using Aspect-Oriented Programming 2 Several patterns crosscut the basic structure of classes adding behav- ior and modifying roles in the classes relationship. As an example you could see the Observer pattern. When you have to implement the pat- tern, you should provide implementation to the Subject and Observer roles. The implementation of this roles adds a set of fields (Subject.observers, Observer.subject) and methods (Attach, Detach, Notify) to the concrete classes or to its superclasses, modifying the original structure of the subject and observer elements. Another example is the Visitor pattern. It’s main goal is to provide a set of operations to a class hierarchy without chang- ing the structure of the underlying classes.
    [Show full text]