Design Pattern Intro/Creational Design Patterns

Total Page:16

File Type:pdf, Size:1020Kb

Design Pattern Intro/Creational Design Patterns CSE316 : FUNDAMENTALS OF SOFTWARE DEVELOPMENT Lecture 14a : Intro to Design Patterns: Creational Design Patterns Topics ■ Intro to Design Patterns – Creational – Structural – Behavioral ■ Builder Pattern ■ Singleton ■ Prototype ■ Factory Method Pattern ■ Abstract Factory Pattern CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 2 Intro to Design Patterns ■ Design patterns – are template solutions to common programming problems – Help us follow OO principles ■ There are several ‘categories’ of design patterns – Creational – These patterns help build objects in some way – Structural – Help assemble larger structures using various composition and aggregation techniques – Behavioral – These patterns are concerned with algorithms, assignment of responsibilities, and interactions between objects CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 3 Creational Patterns ■ Creational Patterns include: – Builder – Singleton – Prototype – Factory Method Pattern – Abstract Factory Pattern CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 4 Builder Pattern ■ Why Builder? – To build an object composed of other objects – The pattern hides the creation of component objects from the main object – The pattern also hides the details of creating the object from the ‘client’ code. CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 5 Builder Pattern ■ Main parts of this pattern: – A Director – This oversees construction of the object – A Builder – An interface that provides methods that build the component objects – A Concrete Builder – This implements the Builder interface to build a specific type of object – A Product Interface – An interface used by product to allow creation of component objects CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 6 Builder Pattern CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 7 // This interface is for an abstract builder Builder Pattern - Example public interface PizzaBuilder { public void addSauce(); public void addCheese(); ■ Example code: Pizza Store with ‘Pizza Builders’ public void addTopings(); public Pizza getPizza(); } // This is a concrete builder for NY style pizza // This is the 'Director' from the Builder Pattern public class NYPizzaBuilder implements PizzaBuilder { public class PizzaStore { private Pizza pizza; private PizzaBuilder pizzaBuilder; public NYPizzaBuilder() { this.pizza = new Pizza(); public PizzaStore(PizzaBuilder pizzaBuilder) { } this.pizzaBuilder = pizzaBuilder; @Override } public void addSauce() { pizza.setSauce("Red"); public Pizza getPizza() { } return pizzaBuilder.getPizza(); @Override } public void addCheese() { pizza.setCheese("Mozzarella"); public void makePizza() { } this.pizzaBuilder.addSauce(); @Override this.pizzaBuilder.addCheese(); public void addTopings() { this.pizzaBuilder.addTopings(); pizza.setToppings("Pepperoni"); } } } @Override public Pizza getPizza() { return this.pizza; } } CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 8 Builder Pattern - Example // Concrete Product: Pizza public class Pizza implements PizzaPlan { private String sauce; private String cheese; public interface PizzaPlan { private String toppings; // This is an interface for a product (Pizza) @Override public void setSauce(String sauce); public void setSauce(String sauce) { public void setCheese(String cheese); this.sauce = sauce; public void setToppings(String toppings); } } public String getSauce() { return sauce; } @Override public void setCheese(String cheese) { this.cheese = cheese; } public String getCheese() { return cheese; } @Override public void setToppings(String toppings) { this.toppings = toppings; } public String getToppings() { return toppings; } public String toString() { return "Pizza with: " + sauce + " sauce, " + cheese + " cheese, and " + toppings + " toppings."; } } CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 9 Builder Pattern - Example // Finally – How to use all this //Another concrete builder… this one for Boston Style public class BostonPizzaBuilder implements PizzaBuilder { public class TestPizzaBuilder { Pizza pizza; public static void main(String[] args) { public BostonPizzaBuilder() { this.pizza = new Pizza(); PizzaBuilder nyPizza = new NYPizzaBuilder(); } PizzaStore pizzaStore = new PizzaStore(nyPizza); @Override pizzaStore.makePizza(); public void addSauce() { Pizza myPizza = pizzaStore.getPizza(); pizza.setSauce("White"); System.out.println("My Pizza: " + myPizza); } @Override PizzaBuilder bostonPizza = new BostonPizzaBuilder(); public void addCheese() { pizzaStore = new PizzaStore(bostonPizza); pizza.setCheese("Feta"); pizzaStore.makePizza(); } Pizza myOtherPizza = pizzaStore.getPizza(); @Override System.out.println("My other pizza: " + myOtherPizza); public void addTopings() { } pizza.setToppings("clam and mushroom"); } } @Override public Pizza getPizza() { return this.pizza; // Output from a test run } } My Pizza: Pizza with: Red sauce, Mozzarella cheese, and Pepperoni toppings. My other pizza: Pizza with: White sauce, Feta cheese, and clam and mushroom toppings. CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 10 Singleton Pattern ■ This pattern: – Supports applications that need an object of which only 1 instance can be created – Useful anywhere there is a single resource to share ■ Example Uses: – Print Spooler – ThreadPool – Memory Manager – Deck of Cards CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 11 Singleton Pattern ■ Components: – The Singleton Class – A single class that enforces creation of only 1 instance ■ Private Constructor ■ A private variable holding the instance of the Singleton ■ public getInstance() method ■ The getInstance() method: 1. Checks if the instance has been created 2. If it has, return that instance (reference) 3. If not, use the Constructor to build the instance and then return the instance CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 12 Singleton Pattern CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 13 Singleton Pattern ■ Example Singleton Code – Counter public class Singleton { public void increment() { count++; private int count; } static Singleton theInstance; public String toString() { return "Count: " + count; private Singleton() { } count = 0; } } public static Singleton getInstance() { if (theInstance == null) { theInstance = new Singleton(); } return theInstance; } CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 14 Singleton Pattern ■ Example Singleton Code – Counter public class UseSingleton { public static void main(String[] args) { // Output from a run: Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); S1: Count: 3 S2: Count: 3 s1.increment(); s2.increment(); s1.increment(); System.out.println("S1: " + s1); System.out.println("S2: " + s2); } } CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 15 Prototype Pattern ■ This pattern: – Allows ‘cloning’ or ‘copying’ an object to create a new object – Allows adding any subclass of a known superclass at runtime – Good when there are numerous classes that you only want to use if needed at runtime – Reduces need for creating subclasses – Useful when creating an object from scratch is expensive CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 16 Prototype Pattern CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 17 Prototype Pattern - Example public class Shape implements Cloneable { // This is the prototype (the PrototypeInterface is ‘Cloneable’) private int id; private String name; private static int lastId = 0; public Shape() { id = ++lastId; name = "Unknown"; } public Shape(String name) { this.name = name; id = ++lastId; } public void setName (String name) { this.name = name; } public void setId(int id) { this.id = id; } public String getName() { return name; } public int getId() { return id; } } CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 18 Prototype Pattern - Example // This is a prototype class which extends the Prototype // Tests the prototype Shape and clonging public class Circle extends Shape { public class UseShape { private int radius; public static void main(String[] args) { public Circle() { Circle firstShape = new Circle(1); super("Circle"); Circle second = (Circle) firstShape.makeCopy(); radius = 1; Circle third = second; } public Circle(int radius) { System.out.println("1st shape: " + firstShape); super("Circle"); System.out.println("second: " + second); this.radius = radius; System.out.println("Circle is made"); System.out.println("C1: " + System.identityHashCode(firstShape)); } System.out.println("C2: " + System.identityHashCode(second)); public Shape makeCopy() { System.out.println("C3: " + System.identityHashCode(third)); Circle circleObject = null; System.out.println("Circle is being cloned"); } try { } circleObject = (Circle) super.clone(); // Following is output from a run } catch (CloneNotSupportedException e) { e.printStackTrace(); Circle is made } Circle is being cloned circleObject.radius = this.radius; 1st shape: I am: Circle, with id=1 and a radius of 1 circleObject.setName(this.getName()); second: I am: Circle, with id=1 and a radius of 1 circleObject.setId(this.getId()); C1: 905544614 return circleObject; C2: 2137589296 } C3: 2137589296 public String toString() { return "I am: " + getName() + ", with id=" + getId() + " and a radius of " + radius; } } CSE316 : Fund of SW Development - Tony Mione, SUNY Korea - 2019 19 Factory Method Pattern ■
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]
  • 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]
  • Learning Javascript Design Patterns
    Learning JavaScript Design Patterns Addy Osmani Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo Learning JavaScript Design Patterns by Addy Osmani Copyright © 2012 Addy Osmani. All rights reserved. Revision History for the : 2012-05-01 Early release revision 1 See http://oreilly.com/catalog/errata.csp?isbn=9781449331818 for release details. ISBN: 978-1-449-33181-8 1335906805 Table of Contents Preface ..................................................................... ix 1. Introduction ........................................................... 1 2. What is a Pattern? ...................................................... 3 We already use patterns everyday 4 3. 'Pattern'-ity Testing, Proto-Patterns & The Rule Of Three ...................... 7 4. The Structure Of A Design Pattern ......................................... 9 5. Writing Design Patterns ................................................. 11 6. Anti-Patterns ......................................................... 13 7. Categories Of Design Pattern ............................................ 15 Creational Design Patterns 15 Structural Design Patterns 16 Behavioral Design Patterns 16 8. Design Pattern Categorization ........................................... 17 A brief note on classes 17 9. JavaScript Design Patterns .............................................. 21 The Creational Pattern 22 The Constructor Pattern 23 Basic Constructors 23 Constructors With Prototypes 24 The Singleton Pattern 24 The Module Pattern 27 iii Modules 27 Object Literals 27 The Module Pattern
    [Show full text]
  • Lecture 26: Creational Patterns
    Creational Patterns CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 26 — 11/29/2012 © Kenneth M. Anderson, 2012 1 Goals of the Lecture • Cover material from Chapters 20-22 of the Textbook • Lessons from Design Patterns: Factories • Singleton Pattern • Object Pool Pattern • Also discuss • Builder Pattern • Lazy Instantiation © Kenneth M. Anderson, 2012 2 Pattern Classification • The Gang of Four classified patterns in three ways • The behavioral patterns are used to manage variation in behaviors (think Strategy pattern) • The structural patterns are useful to integrate existing code into new object-oriented designs (think Bridge) • The creational patterns are used to create objects • Abstract Factory, Builder, Factory Method, Prototype & Singleton © Kenneth M. Anderson, 2012 3 Factories & Their Role in OO Design • It is important to manage the creation of objects • Code that mixes object creation with the use of objects can become quickly non-cohesive • A system may have to deal with a variety of different contexts • with each context requiring a different set of objects • In design patterns, the context determines which concrete implementations need to be present © Kenneth M. Anderson, 2012 4 Factories & Their Role in OO Design • The code to determine the current context, and thus which objects to instantiate, can become complex • with many different conditional statements • If you mix this type of code with the use of the instantiated objects, your code becomes cluttered • often the use scenarios can happen in a few lines of code • if combined with creational code, the operational code gets buried behind the creational code © Kenneth M. Anderson, 2012 5 Factories provide Cohesion • The use of factories can address these issues • The conditional code can be hidden within them • pass in the parameters associated with the current context • and get back the objects you need for the situation • Then use those objects to get your work done • Factories concern themselves just with creation, letting your code focus on other things © Kenneth M.
    [Show full text]
  • Prof. Catalin Boja, Phd [email protected] Source Code Quality
    Design patterns Prof. Catalin Boja, PhD [email protected] http://acs.ase.ro/software-quality-testing Source code quality Principles for writing the code: • Easy to read / understand - clear • Easy to modify - structured • Easy to reuse • Simple (complexity) • Easy to test • Implement patterns for the standard problem Left: Simply Explained: Code Reuse 2009-12- acs.ase.ro [email protected] 03.By Oliver Widder, Webcomics Geek Aad Poke.2 Source code quality Forces that influence it: • Available time (delivery terms) • Costs • The experience of the programmer • Programmer competences • Specifications clarity • Solution complexity • Change rates for specifications, requirements, team, etc http://khristianmcfadyen.com/ acs.ase.ro [email protected] 3 Anti-Pattern: Big ball of mud “A Big Ball of Mud is a haphazardly structured, sprawling, sloppy, duct-tape- and-baling-wire, spaghetti- code jungle.” Brian Foote and Joseph Yoder, Big Ball of Mud, September 1997 acs.ase.ro [email protected] 4 Anti-Pattern: Big ball of mud Where from ? Why ? • Throwaway code - Temporary (Prototyping) solutions to be replaced / rewritten • Cut and Paste code • Adapting code by commenting / deleting other solutions • Very short or unrealistic deadlines • Lack of experience • Lack of standards / procedures acs.ase.ro [email protected] 5 Anti-Pattern: Big ball of mud How do you avoid it? • Rewriting the code (Refactoring) to an acceptable maturity level • Use Clean Code Principles • Design Patterns Implementation acs.ase.ro [email protected] 6 Design-pattern • A pattern is a reusable solution for a standard problem in a given context • Facilitates the reuse of architectures and software design • They are not data structures acs.ase.ro [email protected] 7 Design-pattern “A pattern involves a general “..
    [Show full text]
  • JAVA CONCURRENCY ONLINE TRAINING – Java2aspire
    JAVA CONCURRENCY, JAVA PROFILING, THREAD POOLING, JAVA 8 Features, MAVEN and DESIGN PATTERNS ONLINE TRAINING By K.Ramesh Curriculum THREAD POOLING Day 01: Executor Framework 20 min Day 01: Java Profiling 10 min Day 01: Executor 10 min Day 01: ExecutorService 10 min Day 01: Executors 15 min Day 02: ThreadPoolExecutor 20 min Day 02: BlockingQueue 10 min Day 02: Callable vs Runnable 15 min Day 02: Future 15 min JAVA CONCURRENCY Day 03: ConcurrentHashMap 30 min Day 03: Producer Consumer 30 min Day 04: CountDownLatch 20 min Day 04: CyclicBarrier 20 min Day 04: Deadlock Condition 20 min Day 05: Race Condition 30 min Day 05: Semaphore 30 min JAVA 8 FEATURES Day 06: Lambda Expressions 40 min Day 06: Functional Interfaces 10 min Day 06: Functional Programming 10 min Day 07: Method References 10 min Day 07: Default Methods 40 min Day 07: Optional 10 min Day 08: Stream API 1 hour MAVEN Day 09: Project Object Model (POM) 20 min Day 09: Project Description 10 min Day 09: Public Repository 10 min Day 09: Dependency Management 10 min Day 09: Build Configuration 10 min Day 10: Installation 15 min Day 10: Dependency Scope 15 min Day 10: Proprietary Dependencies 15 min Day 10: Project Inheritance 15 min Day 11: Maven life cycle 20 min Day 11: Maven Directory Structure 20 min Day 11: Archetypes 20 min Day 12: Applications 1 hour DESIGN PATTERNS Day 13: Factory Pattern 20 min Day 13: Abstract Factory Pattern 10 min Day 13: Single Pattern 20 min Day 13: Prototype Pattern 10 min Day 14: Composite Pattern 10 min Day 14: Facade Pattern 15 min Day 14: DAO
    [Show full text]
  • Design Patterns in Ocaml
    Design Patterns in OCaml Antonio Vicente [email protected] Earl Wagner [email protected] Abstract The GOF Design Patterns book is an important piece of any professional programmer's library. These patterns are generally considered to be an indication of good design and development practices. By giving an implementation of these patterns in OCaml we expected to better understand the importance of OCaml's advanced language features and provide other developers with an implementation of these familiar concepts in order to reduce the effort required to learn this language. As in the case of Smalltalk and Scheme+GLOS, OCaml's higher order features allows for simple elegant implementation of some of the patterns while others were much harder due to the OCaml's restrictive type system. 1 Contents 1 Background and Motivation 3 2 Results and Evaluation 3 3 Lessons Learned and Conclusions 4 4 Creational Patterns 5 4.1 Abstract Factory . 5 4.2 Builder . 6 4.3 Factory Method . 6 4.4 Prototype . 7 4.5 Singleton . 8 5 Structural Patterns 8 5.1 Adapter . 8 5.2 Bridge . 8 5.3 Composite . 8 5.4 Decorator . 9 5.5 Facade . 10 5.6 Flyweight . 10 5.7 Proxy . 10 6 Behavior Patterns 11 6.1 Chain of Responsibility . 11 6.2 Command . 12 6.3 Interpreter . 13 6.4 Iterator . 13 6.5 Mediator . 13 6.6 Memento . 13 6.7 Observer . 13 6.8 State . 14 6.9 Strategy . 15 6.10 Template Method . 15 6.11 Visitor . 15 7 References 18 2 1 Background and Motivation Throughout this course we have seen many examples of methodologies and tools that can be used to reduce the burden of working in a software project.
    [Show full text]
  • A Survey of Design Pattern Based Web Applications
    JOURNAL OF OBJECT TECHNOLOGY Online at http://www.jot.fm. Published by ETH Zurich, Chair of Software Engineering ©JOT, 2009 Vol. 8, No. 2, March-April 2009 A Survey of Design Pattern Based Web Applications Sridaran R, Campus Head, ICFAI National College, Vellore-632 006 India. Padmavathi G, Professor and Head, Department of Computer Science, Avinashilingam University for Women, Coimbatore-641 043, India. Iyakutti K, Senior Professor, School of Physics, Madurai Kamaraj University, Madurai-625 019, India. Abstract Pattern-based web applications have become popular since they promote reusability and consistency. In few cases, patterns do not produce the desired effect because of lack of experience in applying them. This situation forces one to think of a suitable re- engineering solution for such applications. The objectives of the paper are three fold. It provides a survey of different pattern-based web applications that will be useful for the application designers. It highlights some of the web applications where patterns have been inappropriately handled. A few re-engineering initiatives for such cases are also analyzed. Key Words: Patterns, Web Applications, Re-engineering, Hypermedia, Semantic web, Partitioning. 1 INTRODUCTION Web application designers need to address many challenges during development in order to comply the quality of service requirements including speed, scalability and security. In recent years numerous non-web based applications have been re-written as web based because of the ever growing business needs. These migration activities are much more complicated and time consuming than a new software development. Most of these challenges are with data handling, organizing, or structuring of the web applications.
    [Show full text]
  • Course Title
    "Charting the Course ... ... to Your Success!" JavaScript Advanced Course Summary Description This course will review the basics of JavaScript and provide instruction on advanced topics such as advanced features of JavaScript functions, Object-Oriented programming in JavaScript (Inheritance, encapsulation) with prototypes, using closures, understanding JavaScript promises and advanced best practices. Objectives At the end of this course, students will be able to: Review Learn function expressions/function declarations/immediately executable functions Use JavaScript objects to implement Inheritance and encapsulation Understand JavaScript closures Learn JavaScript promises Discuss how to best use the advanced topics in this course in your JavaScript projects. Topics Basics Review Object-Oriented Programming Function Expressions Error Handling And Debugging Advanced Techniques Audience This course is intended for JavaScript programmers Prerequisites JavaScript introduction Duration Two days Due to the nature of this material, this document refers to numerous hardware and software products by their trade names. References to other companies and their products are for informational purposes only, and all trademarks are the properties of their respective companies. It is not the intent of ProTech Professional Technical Services, Inc. to use any of these names generically "Charting the Course ... ... to Your Success!" JavaScript Advanced Course Outline I. Basics Review IV. Error Handling And Debugging A. Browser Error Reporting II. Object-Oriented Programming B. Internet Explorer A. Understanding Objects C. Firefox B. Types of Properties D. Chrome C. Defining Multiple Properties E. Error Handling D. Reading Property Attributes F. The try-catch Statement E. Object Creation G. Throwing Errors F. The Factory Pattern H. The error Event G. The Constructor Pattern I.
    [Show full text]
  • Creational Patterns
    9. Creational Pattern Venkat Subramaniam CDP-1 Creational Patterns • Abstracts instantiation process • Makes system independent of how its objects are œ created œ composed œ represented • Encapsulates knowledge about which concrete classes the system uses • Hides how instances of these classes are created and put together Venkat Subramaniam CDP-2 Abstract Factory Provide an interface for creating families of related or dependent objects without specifying their concrete classes Venkat Subramaniam CDP-3 Example that would benefit from Abstract Factory ComputerModelA MemoryType A CPUTypeA ModemTypeA BuildComputer(ComputerModelA& comp) { comp.Add(new MemoryTypeA); comp.Add(new CPUTypeA); comp.Add(new ModemTypeA); } What if I want to build a Computer of Model B with Model B Memory,CPU and Modem? Venkat Subramaniam CDP-4 Using Abstract Factory ComputerFactory Client Computer createComputer() createMemory() createCPU() Computer Computer createModem() ModelA ModelB Memory CompFactoryB CompFactoryA createComputer() createComputer() Memory Memory createMemory() createMemory() ModelA ModelB createCPU() createCPU() createModem() createModem() Venkat Subramaniam CDP-5 Using Abstract Factory... BuildComputer(Computer& comp, ComputerFactory& compFactory) { comp.Add(compFactory.createMemory()) ; comp.Add(compFactory.createCPU()); comp.Add(compFactory.createModem()); } Venkat Subramaniam CDP-6 .hen to use Abstract Factory? • Use Abstract Factory when: œ system should be independent of how its products are created, composed and represented œ system should
    [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]
  • 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]