Object-Oriented Design Case Studies with Patterns &

Total Page:16

File Type:pdf, Size:1020Kb

Object-Oriented Design Case Studies with Patterns & OO Pattern Examples Douglas C. Schmidt Case Studies Using Patterns The following slides describ e several case studies using C++ & patterns to build highly extensible software Object-Oriented Design Case Studies with The examples include Patterns & C++ 1. Expression Tree Douglas C. Schmidt { e.g., Adapter, Factory, Bridge 2. System Sort Professor Department of EECS { e.g., Facade, Adapter, Iterator, Singleton, Factory Metho d, Strategy, [email protected] Vanderbilt University Bridge www.dre.vanderbilt.edu/schmidt/ 615 343-8197 3. Sort Veri er { e.g., Strategy, Factory Metho d, Facade, Iterator, Singleton Vanderbilt University 1 OO Pattern Examples Douglas C. Schmidt OO Pattern Examples Douglas C. Schmidt Case Study: Expression Tree Evaluator Expression Tree Diagram BINARY The following inheritance & dynamic binding example constructs * NODES expression trees { Expression trees consist of no des containing op erators & op erands _ Op erators have di erent precedence levels, di erent asso ciativities, + & di erent arities, e.g., Multiplication takes precedence over addition UNARY The multiplication op erator has two arguments, whereas unary NODE 5 3 44 minus op erator has only one 5 3 Op erands are integers, doubles, variables, etc. We'll just handle integers in this example . INTEGER NODES Vanderbilt University 2 Vanderbilt University 3 V OO V OO anderbilt anderbilt MEMORY LAYOUT Here's Exp { { P P binary_ unary_ attern attern num_ use_ tag_ op_ The T ression rees Return P Generate T e.g. Universit Universit Examples Examples raverse erfo the evaluation , ma Memo in-o rm y y memo trees y the semantic rder, be & ode co \value" Node p Tree \evaluated" ry ry rint RELATIONSHIPS Exp step ost-o p la La y CLASS 1 the out 1|2 ression analysis ma y of rder, out exp y of the erfo p Node a Tree ression via p of struct exp re-o T di erent rm Algo ression ree rder, va tree Tree rious Behavio rithmic level-o traversals tree Node perations, op rder object r V ersion e.g. Douglas Douglas , C. C. Schmidt Schmidt 6 4 o OO Pattern Examples Do OO Pattern Examples D Algorithmic Version Print Tree Function A typical algorithmic implementation use a switch A typical algorithmic metho d for implementing statement & a recursive function to build & evaluate expression trees involves using a struct/union to a tree, e.g., represent data structure, e.g., void print_tree Tree_Node *root { typedef struct Tree_Node Tree_Node; switch root->tag_ { struct Tree_Node { case NUM: printf "d", root->num_; enum { NUM, UNARY, BINARY } tag_; break; short use_; /* reference count */ case UNARY: union { printf "s", root->op_[0]; char op_[2]; print_tree root->unary_; int num_; printf ""; break; } o; case BINARY: define num_ o.num_ printf ""; define op_ o.op_ print_tree root->binary_.l_ ; union { printf "s", root->op_[0]; Tree_Node *unary_; root->binary_.r_ ; print_tree struct { Tree_Node *l_, *r_; } binary_; printf ""; break; } c; default: define unary_ c.unary_ printf "error, unknown type\n"; define binary_ c.binary_ } }; } Vanderbilt University Vanderbilt University OO Pattern Examples Douglas C. Schmidt OO Pattern Examples Douglas C. Schmidt Limitations with Algorithmic Approach More Limitations with Algorithmic Approach Problems or limitations with the typical algorithmic approach include The program organization makes it dicult to extend, e.g., { Little or no use of encapsulation { Any small changes will ripple through the entire design & implementation Incomplete mo deling of the application domain, which results in e.g., see the \ternary" extension b elow { Easy to make mistakes switching on typ e tags . 1. Tight coupling between no des & edges in union representation 2. Complexity b eing in algorithms rather than the data structures Solution wastes space by making worst-case assumptions wrt structs & { e.g., switch statements are used to select between various typ es of unions no des in the expression trees { Compare with binary search! { This is not essential, but typically o ccurs 3. Data structures are \passive" & functions do most pro cessing work { Note that this problem b ecomes worse the bigger the size of the explicitly largest item b ecomes! Vanderbilt University 8 Vanderbilt University 9 OO Pattern Examples Douglas C. Schmidt OO Pattern Examples Douglas C. Schmidt OO Alternative Expression Tree Diagram BINARY Contrast previous algorithmic approach with an object-oriented * NODES decomp osition for the same problem: { Start with OO mo deling of the \expression tree" application domain, _ e.g., go back to original picture + { Discover several classes involved: class No de: base class that describ es expression tree vertices: UNARY class Int No de: used for implicitly converting int to Tree no de NODE class Unary No de: handles unary op erators, e.g., -10, +10, !a 55 33 44 class Binary No de: handles binary op erators, e.g., a + b, 10 - 30 class Tree: \glue" co de that describ es expression-tree edges, i.e., relations between No des INTEGER { Note, these classes mo del entities in the application domain NODES i.e., no des & edges vertices & arcs Vanderbilt University 10 Vanderbilt University 11 OO Pattern Examples Douglas C. Schmidt OO Pattern Examples Douglas C. Schmidt Relationships Between Tree & No de Classes Design Patterns in the Expression Tree Program Binary Unary Int Node Node Node Factory 1 1 { Centralize the assembly of resources necessary to create an object e.g., decouple Node sub class initialization from use Bridge { Decouple an abstraction from its implementation so that the two can Ternary Node vary indep endently Node e.g., printing contents of a subtree and managing memory 2 1 Adapter 1 has-a 3 Tree { Convert the interface of a class into another interface clients exp ect e.g., make Tree conform C++ iostreams Vanderbilt University 12 Vanderbilt University 13 OO Pattern Examples Douglas C. Schmidt OO Pattern Examples Douglas C. Schmidt C++ No de Interface C++ Tree Interface include "Node.h" class Tree; // Forward declaration // Bridge class that describes the Tree edges and // acts as a Factory. // Describes the Tree vertices class Tree { class Node { public: friend class Tree; // Factory operations protected: // Only visible to derived classes Tree int; Node : use_ 1 {} Tree const string &, Tree &; Tree const string &, Tree &, Tree &; /* pure */ virtual void print std::ostream & const = 0; Tree const Tree &t; void operator= const Tree &t; // Important to make destructor virtual! ~Tree ; virtual ~Node ; void print std::ostream & const; private: private: int use_; // Reference counter. Node *node_; // pointer to a rooted subtree }; Vanderbilt University 14 Vanderbilt University 15 OO Pattern Examples Douglas C. Schmidt OO Pattern Examples Douglas C. Schmidt C++ Int No de Interface C++ Unary No de Interface include "Node.h" include "Node.h" class Int_Node : public Node { class Unary_Node : public Node { public: public: Int_Node int k; Unary_Node const string &op, const Tree &t; virtual void print std::ostream &stream const; virtual void print std::ostream &stream const; private: private: int num_; // operand value. string operation_; }; Tree operand_; }; Vanderbilt University 16 Vanderbilt University 17 o D OO Pattern Examples Douglas C. Schmidt C++ Binary No de Interface Node include "Node.h" of ) ) ) op tag ) ) ) op tag ersion PART PART PART PART PART PART left V right left_ PART middle right_ class Binary_Node : public Node { Node PART Node operator middle_ (Tree (Tree operator_ (Tree (Tree (Tree (Tree public: ) ) ) ) Binary_Node const string &op, sub classes Node PART C++ PART PART Ternary PART left right left_ PART const Tree &t1, Node PART right_ Node Node operator Binary r (Tree operator_ (Tree (Tree (Tree const Tree &t2; fo ) ) virtual void print std::ostream &s const; di erent PART PART private: out PART r Node PART operand Node operator operand_ (Tree operator_ (Tree y fo const string operation_; Unary Node La Tree left_; outs y ptr use y ry vptr num vptr use_ Tree right_; PART Tree num_ Node node_ PART Node Node la Int_Node }; ry Examples Universit Memo attern P Memo anderbilt Vanderbilt University 18 OO V OO Pattern Examples Douglas C. Schmidt OO Pattern Examples Douglas C. Schmidt C++ Int No de Implementations C++ Unary No de Implementations include "Int_Node.h" include "Unary_Node.h" Int_Node::Int_Nod e int k: num_ k { } Unary_Node::Unary _N ode const string &op, const Tree &t1 : operation_ op, operand_ t1 { } void Int_Node::print std::ostream &stream const { stream << this->num_; void Unary_Node::print std::ostream &stream const { } stream << "" << this->operation_ << << this->operand_ // recursive call! << ""; } Vanderbilt University 20 Vanderbilt University 21 OO Pattern Examples Douglas C. Schmidt OO Pattern Examples Douglas C. Schmidt C++ Binary No de Implementation Initializing the No de Sub classes include "Binary_Node.h" Problem Binary_Node::Bina ry _No de const string &op, { How to ensure the No de sub classes are initialized prop erly const Tree &t1, Forces const Tree &t2: operation_ op, left_ t1, right_ t2 {} { There are di erent typ es of No de sub classes e.g., take di erent numb er & typ e of arguments void Binary_Node::prin t std::ostream &stream const { { We want to centralize initialization in one place b ecause it is likely to stream << "" << this->left_ // recursive call change . << " " << this->operation_ Solution << " " << this->right_ // recursive call << ""; { Use a Factory pattern to initialize the No de sub classes } Vanderbilt University 22 Vanderbilt University 23 OO Pattern Examples Douglas C. Schmidt OO Pattern Examples Douglas C. Schmidt The Factory Pattern Structure of the Factory Pattern Factory Intent { Centralize the assembly of resources necessary to create an object make_product() Decouple object creation from object use by lo calizing creation knowledge creates This pattern resolves the following forces: Product product = ... { Decouple initialization of the Node sub classes from their subsequent return product use { Makes it easier to change or add new No de sub classes later on e.g., Ternary no des .
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]
  • On the Interaction of Object-Oriented Design Patterns and Programming
    On the Interaction of Object-Oriented Design Patterns and Programming Languages Gerald Baumgartner∗ Konstantin L¨aufer∗∗ Vincent F. Russo∗∗∗ ∗ Department of Computer and Information Science The Ohio State University 395 Dreese Lab., 2015 Neil Ave. Columbus, OH 43210–1277, USA [email protected] ∗∗ Department of Mathematical and Computer Sciences Loyola University Chicago 6525 N. Sheridan Rd. Chicago, IL 60626, USA [email protected] ∗∗∗ Lycos, Inc. 400–2 Totten Pond Rd. Waltham, MA 02154, USA [email protected] February 29, 1996 Abstract Design patterns are distilled from many real systems to catalog common programming practice. However, some object-oriented design patterns are distorted or overly complicated because of the lack of supporting programming language constructs or mechanisms. For this paper, we have analyzed several published design patterns looking for idiomatic ways of working around constraints of the implemen- tation language. From this analysis, we lay a groundwork of general-purpose language constructs and mechanisms that, if provided by a statically typed, object-oriented language, would better support the arXiv:1905.13674v1 [cs.PL] 31 May 2019 implementation of design patterns and, transitively, benefit the construction of many real systems. In particular, our catalog of language constructs includes subtyping separate from inheritance, lexically scoped closure objects independent of classes, and multimethod dispatch. The proposed constructs and mechanisms are not radically new, but rather are adopted from a variety of languages and programming language research and combined in a new, orthogonal manner. We argue that by describing design pat- terns in terms of the proposed constructs and mechanisms, pattern descriptions become simpler and, therefore, accessible to a larger number of language communities.
    [Show full text]
  • Additional Design Pattern Examples Design Patterns--Factory Method
    Additional Design Pattern Examples • Creational – Factory method – Abstract factory • Structural – Decorator – Adapter • Behavioral – Observer Design Patterns--Factory Method • Intent--Permit a class to be reuseable with arbitrary data types. Specifically, allow the class to be independent of the classes it instantiates – Define an interface for object creation. – Let subclasses decide which class to instantiate. • Motivation – Useful for development of frameworks 1 Factory Method--Continued • Consider a document-processing framework – High-level support for creating, opening, saving documents – Consistent method calls for these commands, regardless of document type (word-processor, spreadsheet, etc.) – Logic to implement these commands delegated to specific types of document objects. – May be some operations common to all document types. Factory Method--Continued Document Processing Example-General Framework: Document Application getTitle( ) * Edits 1 newDocument( ) newDocument( ) openDocument( ) openDocument( ) ... ... MyDocument Problem: How can an Application object newDocument( ) create instances of specific document classes openDocument( ) without being application-specific itself. ... 2 Factory Method--Continued Use of a document creation “factory”: Document Application getTitle( ) * Edits 1 newDocument( ) newDocument( ) openDocument( ) openDocument( ) ... ... 1 requestor * Requests-creation creator 1 <<interface>> MyDocument DocumentFactoryIF newDocument( ) createDocument(type:String):Document openDocument( ) ... DocumentFactory
    [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]
  • Design Patterns
    CSE 403: Software Engineering, Winter 2016 courses.cs.washington.edu/courses/cse403/16wi/ Design Patterns Emina Torlak [email protected] Outline • Overview of design patterns • Creational patterns • Structural patterns • Behavioral patterns 2 introoverview of design patterns What is a design pattern? 4 What is a design pattern? • A standard solution to a common programming problem • a design or implementation structure that achieves a particular purpose • a high-level programming idiom 4 What is a design pattern? • A standard solution to a common programming problem • a design or implementation structure that achieves a particular purpose • a high-level programming idiom • A technique for making code more flexible or efficient • reduce coupling among program components • reduce memory overhead 4 What is a design pattern? • A standard solution to a common programming problem • a design or implementation structure that achieves a particular purpose • a high-level programming idiom • A technique for making code more flexible or efficient • reduce coupling among program components • reduce memory overhead • Shorthand for describing program design • a description of connections among program components • the shape of a heap snapshot or object model 4 Why should you care? • You could come up with these solutions on your own … • But you shouldn't have to! • A design pattern is a known solution to a known problem. 5 Types of design patterns • Creational patterns • how objects are instantiated • Structural patterns • how objects / classes can
    [Show full text]
  • Table of Contents
    Table of Contents ± -—T^jTp^om Object-Oriented to Functional Programming 5 Chajava- an introduction 5 java programming paradigms 6 CO imperative programming CD Real-life imperative example Object-oriented paradigm 7 Objects and classes 7 Encapsulation 7 Abstraction 8 Inheritance 8 Polymorphism 9 Declarative programming 10 Functional programming 11 Working with collections versus working with streams 11 An introduction to Unified Modeling Language 12 Class relations 14 Generalization 15 Realization 15 Dependency 16 Association 16 Aggregation 16 Composition 17 Design patterns and principles 17 Single responsibility principle 18 Open/closed principle 20 Liskov Substitution Principle 20 Interface Segregation Principle 22 Dependency inversion principle 23 Summary 24 Chapter 2: Creational Patterns 27 Singleton pattern 27 Synchronized singletons 29 Synchronized singleton with double-checked locking mechanism 30 Lock-free thread-safe singleton 30 tu * y and lazy loacling 31 i he factory pattern 31 Simple factory pattern 32 Table of Contents Static factory 33 Simple factory with class registration using reflection 34 Simple factory with class registration using Product.newlnstance 35 Factory method pattern 36 Anonymous concrete factory 38 Abstract factory 38 Simple factory versus factory method versus abstract factory 40 Builder pattern 40 Car builder example 41 Simplified builder pattern 43 Anonymous builders with method chaining 44 Prototype pattern 45 Shallow clone versus deep clone Object pool pattern Summary аэоэсБ Chapter 3: Behavioral Patterns
    [Show full text]
  • Factory Pattern: Motivation • Consider the Following Scenario: – You Have
    Factory Pattern: Motivation • Consider the following scenario: { You have a superclass (P roduct) and a set of subclasses that inherit from it (P roductSubclass1, P roductSubclass2, ...) { As usual, there are a number of methods that the subclasses share in com- mon, that they inherit from the superclass { You have client code that needs to be able to create objects of the various subclasses ∗ We'll call this the orderProduct method ∗ We'll refer to the created objects as products ∗ To specify to which subclass a product should belong, orderProduct will have a parameter which specifies the type 1 Factory Pattern: Motivation (2) { For example: public class Product { //constructor ... ... step1(...) { //Methods that apply to all subclasses in common ... } ... step2(...) { ... } ... } public class ProductSubclass1 extends Product { ... } public class ProductSubclass2 extends Product { ... } public class ProductClient { ... Product orderProduct (String type) { Product product; if (type.equals("subclass1")) product = new ProductSubclass1(); else if (type.equals("subclass2")) product = new ProductSubclass2(); ... product.step1(); product.step2(); ... return product; } ... } • The problem with this approach - as usual - is limited flexibility { If we want to add new subclasses - types of products - (or remove existing ones), the client's code must be altered { The above design violates the Open/Closed Principle, among others 2 Factory Pattern: The Simple Factory Model • We want to encapsulate what varies { The part that varies is the product creation - We want to encapsulate the code that creates new products { To accomplish this, we'll create a new class that we'll call a factory { It's purpose is to create new products of a desired type { The client will have an instance variable for the factory ∗ The factory will be used from within the orderP roduct method of the client to create products 3 Factory Pattern: The Simple Factory Model (2) • Sample code: //Superclass and subclasses as before public class ProductSubclass1 extends Product { ..
    [Show full text]
  • Abstract Factory Pattern Real World Example
    Abstract Factory Pattern Real World Example Sparry Reuven blackmails some spiritual and outact his swimming so fumblingly! Gasper remains unilateral: she embow her observatories allegorize too ninefold? Whining Dirk wince some menstruation and traps his Alain-Fournier so banteringly! Can You Improve This Article? Abstract factory code and features, when there are different flavors of elements of each service and every shape based on objects will implement modular gui design pattern real object step is. Do this pattern is hard before uploading a level, we are prototypical instance creation logic on desktop or dependent products are design pattern is often. Living in real world design pattern real factory world example, real world has a generic interfaces that will post helpful example, amazon web api like services. If i like this Decorator design pattern tutorial in Java then my share remains your friends and colleagues. Let's you factory method with own factory voil here read the. So basically, we release another attribute of abstraction which will identify the location and internally use again car factory implementation without even giving a single hint you the user. Sometimes, it think of patterns as recipes. It is not related to that. This is the Elven Army! In their state, we have been made up of objects of objects. What medium the intent of the merit Pool pattern? Given a real object as needed. This differs from the Observer pattern determined it allows any subscriber implementing an advance event handler to register what and vague topic notifications broadcast radio the publisher. And think is real world you have new instance property from a partial classes one place here abstract container, we have no review stack exchange is not.
    [Show full text]
  • Template Method, Factory Method, and Composite
    CHAPTER 7 Template Method, Factory Method, and Composite Objectives The objectives of this chapter are to identify the following: • Introduce the template, factory, and composite patterns. • Create basic UML diagrams for these design patterns. • Review the UML collaboration and deployment diagrams. Software Development Methods 1 Template Method, Factory Method, and Composite Template Method Use the Template Method pattern to: Pattern • Define a skeleton of an algorithm in a base class but defer certain steps to derived classes. This allows a subclass to provide a specific implementation for a single step within an algorithm without using the strategy or bridge pat- terns. Template Methods have two (2) participants: • An Abstract Class which defines the abstract operations that will be imple- mented by the concrete subclasses. This class also defines the skeleton of the algorithm. • A Concrete Class which implements the primitive abstract methods declared in the abstract class. The results we gain from implementing a Template Method pattern are: • An inverted control structure. The parent class, via inheritance and polymor- phism, calls the derived class’ methods and not vice versa. To illustrate this design pattern, the following trivial example: class ClassA { protected: virtual void doPrint(void) = 0; public: void print(void); }; The Java equivalent might appear as: public class ClassA { protected abstract void doPrint(); public void print() { ... } }; Now we implement the print() method in the abstract class: void ClassA::print() { // do some stuff doPrint(); // do more stuff } The corresponding Java code might appear as: 2 Software Development Methods Template Method, Factory Method, and Composite public void print() { // do some stuff doPrint(); // do more stuff } No we need to define the doPrint() method.
    [Show full text]
  • Executive Summary: Balking Design Patterns by Drew Goldberg
    Executive Summary: Balking Design Patterns By Drew Goldberg Balking Patterns are used to prevent an object from executing certain code if it is an incomplete or inappropriate state. These Design Patterns include: The Balking Pattern, The Guarded Suspension, and The Double-Checked Locking Pattern. These patterns seem to have arisen when JVMs were slower and synchronization wasn't as well understood as it is today. These patterns have appeared become somewhat antiquated as JVMs improved, newer design pattern(s) were introduced, and the increased use of functional programming language's immutable/persistent data structures help reduce the complexities of concurrency's implementation and maintenance. Still it is nice to see what was used in the past inorder to get a better perspective of today's concurrency techniques. Balking - Design Patterns Dealing with Incomplete and Incorrect States By Drew Goldberg What are balking patterns? ● Balking - If an object’s method is invoked when the object is in an inappropriate state, then the method will return without doing anything. Balking Design Patterns: ● Balking Design Pattern ● Guarded Suspension ● Double Checked Locking Reference: http://www.mindspring.com/~mgrand/pattern_synopses.htm#Balking Balking Pattern: Intro ● This software design pattern is used to invoke an action on an object only when the object is in a particular state. ● Objects that use this pattern are generally only in a state that is prone to balking temporarily but for an unknown amount of time reference: http://en.wikipedia.org/wiki/Balking_pattern Balking Pattern: Implementation public class Example { private boolean jobInProgress = false; public void job() { synchronized(this) { If the boolean instance variable if (jobInProgress) { jobInProgress is set to false, then return; the job() will return without having } jobInProgress = true; executed any commands and } therefore keeping the object's // Code to execute job goes here state the same.
    [Show full text]
  • A Methodology for the Automated Introduction of Design Patterns
    A Methodology for the Automated Introduction of Design Patterns Mel Ó Cinnéide Paddy Nixon Department of Computer Science Department of Computer Science University College Dublin Trinity College Dublin Ireland. Ireland. [email protected] [email protected] Abstract simply creating a new method or moving an existing method. One interesting category of higher-level In reengineering legacy code it is frequently useful to transformation that a designer may wish to apply introduce a design pattern in order to add clarity to the comprises those transformations that introduce design system and thus facilitate further program evolution. We patterns [10]. Design patterns loosen the binding between show that this type of transformation can be automated in program components thus enabling certain types of a pragmatic manner and present a methodology for the program evolution to occur with minimal change to the development of design pattern transformations. We program itself. For example, the creation of a Product address the issues of the definition of a starting point for object within a Creator class could be replaced by an the transformation, the decomposition of a pattern into application of the Factory Method pattern (See appendix minipatterns and the development of corresponding A for a brief description of design patterns and the minitransformations that can introduce these Factory Method pattern in particular). This enables the minipatterns to a program. We argue that behaviour Creator class to be extended to use another type of preservation is a key issue and develop a rigorous Product object without significant reworking of the argument of this for each minitransformation we existing code.
    [Show full text]