Factory Pattern: Motivation • Consider the Following Scenario: – You Have

Total Page:16

File Type:pdf, Size:1020Kb

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 { ... } public class ProductSubclass2 extends Product { ... } public class SimpleFactory { public Product createSubclassProduct (String type) { Product product null; if (type.equals("subclass1")) product = new ProductSubclass1(); else if (type.equals("subclass2")) product = new ProductSubclass2(); ... return product; } public class Client { SimpleFactory factory; public Client (SimpleFactory factory) { this.factory = factory;) } Product orderProduct (String type) { Product product; product = factory.createSubclassProduct(type); product.step1(); product.step2(); ... return product; } ... } 4 Factory Pattern: The Simple Factory Model (3) • Summary of the changes: 1. Create a new factory class { The factory implements the method for creating new products { This code had originally been in the client 2. Remove the product creation method from the client { Replace it with a call to the product creation method in the factory 3. Add an instance variable for the factory in the client { Its value is passed in via the constructor • Class diagram: • Simple Factory is not a true pattern 5 Factory Pattern: Further Considerations • Suppose you now want to have different types of clients { Each client type produces the same set of products, but { Each product of a given subclass varies in some way from client type to client type • We can think of each client type as representing a category for the subclasses { For example , there is a 1. A category1 for ProductSubclass1, ProductSubclass2, ...; 2. A category2 for ProductSubclass1, ProductSubclass2, ..., etc. ∗ Each category makes products for the same set of subclasses ∗ But each category produces them with slightly different characteristics { For the subclasses, some inherited methods may be implemented exactly the same no matter what category a product belongs to { Other methods may differ based on the category of the product**** • One approach would be to have a factory for each category { A factory for category1 { A factory for category2 { ... 6 Factory Pattern: Further Considerations (2) • Class diagram: • Sample driver code: Category1Factory factory1 = new Category1Factory(); Client cat1Client = new Client(factory1); cat1Client.orderProduct("class1"); Category2Factory factory2 = new Category2Factory(); Client cat2Client = new Client(factory2); cat2Client.orderProduct("class1"); 7 Factory Pattern: Further Considerations (3) { In the above example ∗ Two factories are created: 1. One for creating category1 products 2. One for creating category2 products ∗ Two objects are created: 1. cat1Client, which "orders" class1-type products from a category1 fac- tory 2. cat2Client, which "orders" class1-type products from a category2 fac- tory ∗ Both clients end up with class1 products, but they differ as per the category to which they belong • A better approach would be to link the product creation back to the client, but with more flexibility than our original approach had { To achieve the flexibilty of having product creation back in the client: 1. Make an abstract class for clients (Client) 2. Move the createP roduct method back into the Client class ∗ This method becomes abstract here ∗ With the createP roduct back in the Client class, Client becomes a superclass for factories 3. Make a client subclass for each category (Category1F actory, Category2F actory, ...) ∗ These subclasses inherit from Client ∗ Since createP roduct is abstract in Client, each of these subclasses must implement it ∗ These implementations will reflect the variations peculiar to the cat- egory ∗ The subclasses are the actual factories 4. We still have a generic P roduct class 5. Create a subclass for each combination of product subclass and category ∗ The subclasses all inherit from the P roduct class 8 Factory Pattern: Further Considerations (4) { Class diagram: 9 Factory Pattern: Further Considerations (5) { Code: public abstract class Client { public Product orderProduct(String type) { Product product; product = createProduct(type); product.step1(...); product.step2(...); ... return product; } abstract Product createProduct(String type); } public abstract class Product { ... step1(...) { //Methods that apply to all subclasses in common ... } ... step2(...) { ... } ... } public class Category1Factory extends Client { ... Product createProduct (String type) { if (type.equals("subclass1")) return new Category1Subclass1Product(); else if (type.equals("subclass2")) return new Category1Subclass2Product(); ... else return null; } ... } 10 Factory Pattern: Further Considerations (6) public class Category1Subclass1Product extends Product { //constructor //Override any steps that are specific to Catgory1Subclass1 products ... } public class Driver { public static void main (String[] arge) { Client cat1Factory = new Category1Factory(); Client cat2Factory = new category2Factory(); Product product = cat1Factory.orderProduct("type2"); product = cat2Factory.orderProduct("type2"); ... } 11 Factory Pattern: The Factory Method Pattern Defined • The Factory Pattern (p 134): Defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantia- tion to subclasses. • Class diagram: • The pattern encapsulates the instantiation of concrete types 1. The Creator class provides an interface for creating products { It defines the factory structure 2. The concrete subclasses of Creator actually generate the products 3. Methods in Creator other than factoryMethod are used only to operate on the products • "Deciding by subclasses" is a bit misleading { It's the user/programer who actually decides what subclass will be instan- tiated { The use of "decides" is meant to imply loose coupling between the client and Creator { Creator doesn't know what products are being created 12 Factory Pattern: The Factory Method Pattern Defined (2) • Even when only a single concrete creator is needed, the Factory Method is warranted { It decouples the implementation of a product from its use { It facilitates addition of additional concrete creators { It facilitates modification of implementation • While similar to the Simple Factory, Factory is different { In Simple Factory, the factory is composed with the client { In Factory, each client must implement the factory method • Creator and factoryMethod can be concrete { This allows creation of products even when there are no subclasses • There can be a single type of product rather than variations (types) { In such cases, no parameter needs to be passed to the factory method 13 Factory Pattern: Dependency Inversion Principle • The Dependency Inversion Principle (p 139) (Principle 6) Depend upon abstractions. Do not depend upon concrete classes. • It imposes a stricter condition than the "Program to an interface, not an im- plementation" Principle { High-level components should not depend on low-level ones { Both should depend on abstractions { This is an "inversion" of the usual type of thinking in OO design • In our original approach (Factory Pattern Motivation), if we had taken into account categories of products, we would have ended up with code similar to public class Client { public Product createProduct (String category, String type) { Product product = null; if (category.equals("category1")) if (type.equals("type1")) product = new Category1Subclass1(); else if (type.equals("type2")) product = new Category1Subclass2(); ... if (category.equals("category2")) if (type.equals("type1")) product = new Category2Subclass1(); else
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]
  • A Design Pattern Detection Tool for Code Reuse
    DP-CORE: A Design Pattern Detection Tool for Code Reuse Themistoklis Diamantopoulos, Antonis Noutsos and Andreas Symeonidis Electrical and Computer Engineering Dept., Aristotle University of Thessaloniki, Thessaloniki, Greece [email protected], [email protected], [email protected] Keywords: Design Pattern Detection, Static Code Analysis, Reverse Engineering, Code Reuse. Abstract: In order to maintain, extend or reuse software projects one has to primarily understand what a system does and how well it does it. And, while in some cases information on system functionality exists, information covering the non-functional aspects is usually unavailable. Thus, one has to infer such knowledge by extracting design patterns directly from the source code. Several tools have been developed to identify design patterns, however most of them are limited to compilable and in most cases executable code, they rely on complex representations, and do not offer the developer any control over the detected patterns. In this paper we present DP-CORE, a design pattern detection tool that defines a highly descriptive representation to detect known and define custom patterns. DP-CORE is flexible, identifying exact and approximate pattern versions even in non-compilable code. Our analysis indicates that DP-CORE provides an efficient alternative to existing design pattern detection tools. 1 INTRODUCTION ecutable. As a result, developers cannot exploit the source code of other systems without first resolving Developers need to understand existing projects in or- their dependencies and executing them correctly. Sec- der to maintain, extend, or reuse them. However, un- ondly, pattern representations in most tools are not in- derstanding usually comes down to understanding the tuitive, thus resulting in black box systems that do not source code of a project, which is inherently difficult, allow the developer any control over the detected pat- especially when the original software architecture and terns.
    [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]
  • 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]
  • A Design Pattern Generation Tool
    Project Number: GFP 0801 A DESIGN PATTERN GEN ERATION TOOL A MAJOR QUALIFYING P ROJECT REPORT SUBMITTED TO THE FAC ULTY OF WORCESTER POLYTECHNIC INSTITUTE IN PARTIAL FULFILLME NT OF THE REQUIREMEN TS FOR THE DEGREE OF BACHELOR O F SCIENCE BY CAITLIN VANDYKE APRIL 23, 2009 APPROVED: PROFESSOR GARY POLLICE, ADVISOR 1 ABSTRACT This project determines the feasibility of a tool that, given code, can convert it into equivalent code (e.g. code that performs the same task) in the form of a specified design pattern. The goal is to produce an Eclipse plugin that performs this task with minimal input, such as special tags.. The final edition of this plugin will be released to the Eclipse community. ACKNOWLEGEMENTS This project was completed by Caitlin Vandyke with gratitude to Gary Pollice for his advice and assistance, as well as reference materials and troubleshooting. 2 TABLE OF CONTENTS Abstract ....................................................................................................................................................................................... 2 Acknowlegements ................................................................................................................................................................... 2 Table of Contents ..................................................................................................................................................................... 3 Table of Illustrations .............................................................................................................................................................
    [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]
  • Abstract Factory and Singleton Design Patterns to Create Decorator Pattern Objects in Web Application
    International Journal of Advanced Information Technology (IJAIT) Vol. 1, No.5, October 2011 ABSTRACT FACTORY AND SINGLETON DESIGN PATTERNS TO CREATE DECORATOR PATTERN OBJECTS IN WEB APPLICATION Vijay K Kerji Department of Computer Science and Engineering, PDA College of Engineering,Gulbarga, India [email protected] ABSTRACT Software Design Patterns are reusable designs providing common solutions to the similar kind of problems in software development. Creational patterns are that category of design patterns which aid in how objects are created, composed and represented. They abstract the creation of objects from clients thus making the application more adaptable to future requirements changes. In this work, it has been proposed and implemented the creation of objects involved in Decorator Design Pattern. (Decorator Pattern Adds Additional responsibilities to the individual objects dynamically and transparently without affecting other objects). This enhanced the reusability of the application design, made application more adaptable to future requirement changes and eased the system maintenance. Proposed DMS (Development Management System) web application is implemented using .NET framework, ASP.NET and C#. KEYWORDS Design Patterns, Abstract Factory, Singleton, Decorator, Reusability, Web Application 1. INTRODUCTION Design Patterns refer to reusable or repeatable solutions that aim to solve similar design problems during development process. Various design patterns are available to support development process. Each pattern provides the main solution for particular problem. From developer’s perspectives, design patterns produce a more maintainable design. While from user’s perspectives, the solutions provided by design patterns will enhance the usability of web applications [1] [2]. Normally, developers use their own design for a given software requirement, which may be new each time they design for a similar requirement.
    [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]
  • Design Patterns Past and Future
    Proceedings of Informing Science & IT Education Conference (InSITE) 2011 Design Patterns Past and Future Aleksandar Bulajic Metropolitan University, Belgrade, Serbia [email protected]; [email protected] Abstract A very important part of the software development process is service or component internal de- sign and implementation. Design Patterns (Gamma et al., 1995) provide list of the common pat- terns used in the object-oriented software design process. The primary goal of the Design Patterns is to reuse good practice in the design of new developed components or applications. Another important reason of using Design Patterns is improving common application design understand- ing and reducing communication overhead by reusing the same generic names for implemented solution. Patterns are designed to capture best practice in a specific domain. A pattern is supposed to present a problem and a solution that is supported by an example. It is always worth to listen to an expert advice, but keep in mind that common sense should decide about particular implemen- tation, even in case when are used already proven Design Patterns. Critical view and frequent and well designed testing would give an answer about design validity and a quality. Design Patterns are templates and cannot be blindly copied. Each design pattern records design idea and shall be adapted to particular implementation. Using time to research and analyze existing solutions is recommendation supported by large number of experts and authorities and fits very well in the pattern basic philosophy; reuse solution that you know has been successfully implemented in the past. Sections 2 and 3 are dedicated to the Design Patterns history and theory as well as literature sur- vey.
    [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]