Java Design Patterns I

Total Page:16

File Type:pdf, Size:1020Kb

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.............................................. 16 4 Composite Design Pattern 17 4.1 Introduction...................................................... 17 4.2 What is the Composite Pattern............................................ 17 4.3 Example of Composite Pattern............................................ 19 4.4 When to use Composite Pattern............................................ 23 4.5 Download the Source Code.............................................. 23 Java Design Patterns iii 5 Bridge Design Pattern 24 5.1 Introduction...................................................... 24 5.2 What is Bridge Pattern................................................ 25 5.3 Solution to the Problem................................................ 26 5.4 Use of Bridge Pattern................................................. 30 5.5 Download the Source Code.............................................. 30 6 Singleton Design Pattern 31 6.1 Singleton Pattern................................................... 31 6.2 How to create a class using the Singleton Pattern.................................. 31 6.3 When to use Singleton................................................ 35 6.4 Download the Source Code.............................................. 35 7 Observer Design Pattern 36 7.1 Observer Pattern................................................... 36 7.2 What is the Observer Pattern............................................. 36 7.3 Implementing Observer Pattern............................................ 37 7.4 Java’s built-in Observer Pattern............................................ 42 7.5 When to use the Observer Pattern........................................... 44 7.6 Download the Source Code.............................................. 44 8 Mediator Design Pattern 45 8.1 Introduction...................................................... 45 8.2 What is the Mediator Pattern............................................. 46 8.3 Implementing the Mediator Pattern.......................................... 47 8.4 When to use the Mediator Pattern.......................................... 53 8.5 Mediator Pattern in JDK............................................... 54 8.6 Download the Source Code.............................................. 54 9 Proxy Design Pattern 55 9.1 Introduction...................................................... 55 9.2 What is the Proxy Pattern............................................... 55 9.3 Remote Proxy..................................................... 56 9.4 Virtual Proxy..................................................... 58 9.5 Protection Proxy................................................... 62 9.6 When to use the Proxy Pattern............................................ 65 9.7 Other Proxies..................................................... 65 9.8 Proxy Pattern in JDK................................................. 65 9.9 Download the Source Code.............................................. 65 Java Design Patterns iv 10 Chain of Responsibility Design Pattern 66 10.1 Chain of Responsibility Pattern............................................ 66 10.2 What is the Chain of Responsibility Pattern..................................... 66 10.3 Implementing Chain of Responsibility........................................ 67 10.4 When to use the Chain of Responsibility Pattern................................... 73 10.5 Chain of Responsibility in JDK............................................ 73 10.6 Download the Source Code.............................................. 74 11 Flyweight Design Pattern 75 11.1 Flyweight Pattern................................................... 75 11.2 What is the Flyweight Pattern............................................. 76 11.3 Solution to the Problem................................................ 77 11.4 When to use the Flyweight Pattern.......................................... 80 11.5 Flyweight in the JDK................................................. 80 11.6 Download the Source Code.............................................. 81 12 Builder Design Pattern 82 12.1 Builder Pattern.................................................... 82 12.2 What is the Builder Pattern.............................................. 82 12.3 Implementing the Builder Pattern........................................... 84 12.4 Another form of the Builder Pattern......................................... 88 12.5 When to use the Builder Pattern........................................... 93 12.6 Builder Pattern in JDK................................................ 93 12.7 Download the Source Code.............................................. 93 13 Factory Method Design Pattern 94 13.1 Introduction...................................................... 94 13.2 What is the Factory Method Pattern......................................... 94 13.3 Implementing Factory Method Pattern........................................ 95 13.4 When to use the Factory Method Pattern....................................... 98 13.5 Factory Method Pattern in JDK............................................ 98 13.6 Download the Source Code.............................................. 98 14 Abstract Factory Method Design Pattern 99 14.1 Introduction...................................................... 99 14.2 What is the Abstract Factory Design Pattern..................................... 99 14.3 Implementing the Abstract Factory Design Pattern.................................. 100 14.4 When to use the Abstract Factory Design Pattern.................................. 104 14.5 Abstract Factory Pattern in JDK........................................... 104 14.6 Download the Source Code.............................................. 105 Java Design Patterns v 15 Prototype Design Pattern 106 15.1 Introduction...................................................... 106 15.2 What is the Prototype Design Pattern......................................... 106 15.3 Solution to the Problem................................................ 107 15.4 When to use the Prototype Design Pattern...................................... 110 15.5 Prototype Pattern in JDK............................................... 110 15.6 Download the Source Code.............................................. 111 16 Memento Design Pattern 112 16.1 Introduction...................................................... 112 16.2 What is the Memento Design Pattern......................................... 112 16.3 Implementing the Memento Design Pattern..................................... 113 16.4 When to use the Memento Pattern.......................................... 117 16.5 Memento Pattern in JDK............................................... 117 16.6 Download the Source Code.............................................. 117 17 Template Design Pattern 118 17.1 Introduction...................................................... 118 17.2 What is the Template Design Pattern......................................... 118 17.3 Implementing the Template Design Pattern...................................... 119 17.4 Introducing a hook inside the template........................................ 122 17.5 When to use the Template Design Pattern...................................... 124 17.6 Template Pattern in JDK............................................... 124 17.7 Download the Source Code.............................................. 124 18 State Design Pattern 125 18.1 Introduction...................................................... 125 18.2 What is the State Design Pattern........................................... 125 18.3 Implementing the State Design Pattern........................................ 126 18.4 When to use the State Design Pattern......................................... 132 18.5 State Design Pattern in Java.............................................. 132 18.6 Download the Source Code.............................................. 132 19 Strategy Design Pattern 133 19.1 Introduction.....................................................
Recommended publications
  • (GOF) Java Design Patterns Mock Exams
    Gang of Four (GOF) Java Design Patterns Mock Exams http://www.JavaChamp.com Open Certification Plattform Authors: N. Ibrahim, Y. Ibrahim Copyright (c) 2009-2010 Introducing JavaChamp.com Website JavaChamp.com is an Open Certification Platform. What does this mean? JavaChamp is the best place to learn, share, and certify your professional skills. We help you develop yourself in the field of computer science and programming Here are the most significant features offered by JavaChamp: Online Exams Start Online Certification Exams in SCJP, SCEA, EJB, JMS, JPA and more... Top quality mock exams for SCJP, SCEA, EJB, JMS, JPA. Start Express or topic-wise customized exam. * We offer you unlimited free mock exams * Exams cover subjects like SCJP, SCEA, EJB, JMS, JPA,.. * You can take as many exams as you want and at any time and for no charges * Each exam contains 20 multiple choice questions * You can save the exams taken in your exams history * Your exams history saves the exams you took, the scores you got, time took you to finish the exam, date of examination and also saves your answers to the questions for later revision * You can re-take the same exam to monitor your progress * Your exams history helps the system to offer you variant new questions every time you take a new exam, therefore we encourage you to register and maintain an exams history Network Find guidance through the maze, meet Study-Mates, Coaches or Trainees... Studying together is fun, productive and helps you in building your professional network and collecting leads Bookshelf JavaChamp Bookshelf full of PDF eBooks..
    [Show full text]
  • Usage of Factory Design Pattern
    What is a Creational Pattern? Creational Patterns are concerned with object creation problems faced during software design. Object creation often results in design problems, creational patterns solve this problem by controlling the object creation. Factory pattern A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class. The Factory Method Pattern is also known as Virtual Constructor. A Factory returns an instance of an object based on the data supplied to it. The instance returned can be one of many classes that extend a common parent class or interface. ("Animal" as a parent class, then "Dog", "Cat", "Zebra" as child classes.) Create objects without exposing their instantiation logic. Consequences: The requestor is independent of the concrete object that is created (how that object is created, and which class is actually created). Advantage of Factory Design Pattern Factory Method Pattern allows the sub-classes to choose the type of objects to create. It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class, so that it will work with any classes that implement that interface or that extends that abstract class. Usage of Factory Design Pattern When a class doesn't know what sub-classes will be required to create When a class wants that its sub-classes specify the objects to be created.
    [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]
  • 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]
  • The Command Dispatcher Pattern Benoit Dupire and Eduardo B Fernandez {[email protected], [email protected]}
    The Command Dispatcher Pattern Benoit Dupire and Eduardo B Fernandez {[email protected], [email protected]} Department of Computer Science and Engineering. Florida Atlantic University Boca Raton, FL 33431 Can also be called: Command Evaluator Pattern. Intent This pattern increases the flexibility of applications by enabling their services to be changed, by adding, replacing or removing any command handlers at any point in time without having to modify, recompile or statically relink the application. By simulating the command-evaluation feature common in interpreted languages, this pattern supports the need for continual, incremental evolution of applications. Example Autonomous Underwater Vehicles (AUVs) are small, unmanned, untethered submersibles. There are numerous applications for AUVs, such as oceanographic surveys, operations in hazardous environments, underwater structure inspection and military operations. We implement the high level controller of this AUV as a Hierarchical Finite State Machine (Figure 1). A state of the Finite State Machine (FSM) represents a mode of the system, in which some tasks have to be executed, as described in the mission plan. The system takes transitions based on the results of these actions and the progression of the AUV. The system is programmed with high-level commands of the style "set depth 3" state1 state2 action 1.1 action 2.1 Figure 1: Simplified Finite State Machine for the AUV. The FSM must be able to fire any type of actions, without knowing anything about them. This problem is addressed by the Command Pattern [GOF95], which encapsulates an action as an object, thereby letting you parameterize clients with different actions.
    [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]
  • 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]
  • Principles of Design
    Principles of Design Balance Proportion/Scale Emphasis Rhythm Introduction The principles of design are essential to the development and production of clothing used by individuals and families around the world. Each principle has a specific role in creating an aesthetically pleasing garment or ensemble. The principles of design consist of: balance, proportion (also referred to as scale), emphasis, and rhythm. When a garment or ensemble uses the elements and principles of design to create a visual unity, harmony is achieved. Garments often integrate more than one principle, while drawing from the elements of design to create a cohesive look. The following discussion will present background information on each of the principles of design and applications to clothing design and construction. Balance According to Wolfe (2011) balance implies that there is an equilibrium or uniformity among the parts of a design (p. 205). To achieve balance, a garment or ensemble should have equal visual weight throughout the design. The use of structural features, added embellishments, or decorations to a garment contribute to the appearance of a garment or ensemble being balanced or not. A clothing designer can utilize surface designs on fabric to construct a garment creating visual balance. Further, color, line, and texture can impact the balance of a design. For example, cool and light colors have less visual weight than dark, warm colors. If an individual is wearing a small amount of a dark, warm color it can be balanced out with a larger amount of cool, light colors. Balance used in clothing design can be categorized into two groups: Formal and Informal Balance.
    [Show full text]
  • Enterprise Development with Flex
    Enterprise Development with Flex Enterprise Development with Flex Yakov Fain, Victor Rasputnis, and Anatole Tartakovsky Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo Enterprise Development with Flex by Yakov Fain, Victor Rasputnis, and Anatole Tartakovsky Copyright © 2010 Yakov Fain, Victor Rasputnis, and Anatole Tartakovsky.. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected]. Editor: Mary E. Treseler Indexer: Ellen Troutman Development Editor: Linda Laflamme Cover Designer: Karen Montgomery Production Editor: Adam Zaremba Interior Designer: David Futato Copyeditor: Nancy Kotary Illustrator: Robert Romano Proofreader: Sada Preisch Printing History: March 2010: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Enterprise Development with Flex, the image of red-crested wood-quails, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein.
    [Show full text]
  • A Mathematical Approach to Object Oriented Design Patterns
    06.2006 J.Natn.Sci.FoundationObject oriented design Sripatterns Lanka 2008 36 (3):219-227 219 RESEARCH ARTICLE A mathematical approach to object oriented design patterns Saluka R. Kodituwakku1*and Peter Bertok2 1 Department of Statistics and Computer Science, Faculty of Science, University of Peradeniya, Peradeniya. 2 Department of Computer Science, RMIT University, Melbourne, Australia. Revised: 27 May 2008 ; Accepted: 18 July 2008 Abstract: Although design patterns are reusable design the distribution of responsibilities. For ease of learning elements, existing pattern descriptions focus on specific and reference, in1, design patterns are organized into a solutions that are not easily reusable in new designs. This paper catalogue. introduces a new pattern description method for object oriented design patterns. The description method aims at providing a The catalogue is formed by two criteria: purpose more general description of patterns so that patterns can be and scope. According to their purpose, design patterns readily reusable. This method also helps a programmer to are classified into creational, structural and behavioural, analyze, compare patterns, and detect patterns from existing software programmes. whereas the scope divides patterns into class patterns and object patterns. Class patterns capture relationships This method differs from the existing pattern description between classes and their subclasses; object patterns deal methods in that it captures both static and dynamic properties with relationships between objects. of patterns. It describes them in terms of mathematical entities rather than natural language narratives, incomplete graphical Software patterns provide reusable solutions to notations or programme fragments. It also helps users to recurring design problems. Even if we have reusable understand the patterns and relationships between them; and solutions they may not be effectively reused, because select appropriate patterns to the problem at hand.
    [Show full text]
  • The Scalable Adapter Design Pattern: Enabling Interoperability Between Educational Software Tools
    The Scalable Adapter Design Pattern: Enabling Interoperability Between Educational Software Tools Andreas Harrer, Catholic University Eichstatt-Ingolstadt,¨ Germany, Niels Pinkwart, Clausthal University of Technology, Germany, Bruce M. McLaren, Carnegie Mellon University, Pittsburgh PA, U.S.A., and DFKI, Saarbrucken,¨ Germany, and Oliver Scheuer, DFKI, Saarbrucken,¨ Germany Abstract For many practical learning scenarios, the integrated use of more than one learning tool is educationally beneficial. In these cases, interoperability between learning tools - getting the pieces to talk to one another in a coherent, well-founded manner - is a crucial requirement that is often hard to achieve. This paper describes a re-usable software design that aims at the integration of independent learning tools into one collaborative learning scenario. We motivate the usefulness and expressiveness of combining several learning tools into one integrated learning experience. Based on this we sketch software design principles that integrate several existing components into a joint technical framework. The feasibility of the approach, which we name the “Scalable Adapter” design pattern, is shown with several implementation examples from different educational technology domains, including Intelligent Tutoring Systems and collaborative learning environments. IEEE keywords: J.m Computer applications, H.5.3 Group and Organization interfaces, K.3.m Computers in Education A short version of this paper appeared in the Proceedings of the Conference on Intelligent Tutoring Systems 2008 1 The Scalable Adapter Design Pattern: Enabling Interoperability Between Educational Software Tools1 I. INTRODUCTION hypothesis and plans. In order to help the student or student In the field of educational technology, there have been groups during the different steps of this inquiry procedure, it numerous attempts in recent years to connect differently makes sense to enable them to have hypotheses, experimenta- targeted learning environments to one another.
    [Show full text]