Design Patterns. Dependency Injection. Oliver Haase

Size: px
Start display at page:

Download "Design Patterns. Dependency Injection. Oliver Haase"

Transcription

1 Design Patterns Dependency Injection Oliver Haase 1

2 Motivation A simple, motivating example (by Martin Fowler): public interface MovieFinder { /** * returns all movies of this finder s source all movies */ List<Movie> findall(); public class ColonDelimitedMovieFinder implements MovieFinder { private final String filename; public ColonDelimitedMovieFinder(String filename) { this.filename = filename; /** * returns all movies listed in file <code>filename</code> List<Movie> findall() { 2

3 Motivation A simple, motivating example (by Martin //assuming that ColonDelimitedMovieFinder is threadsafe public class MovieLister { private final MovieFinder finder; public MovieLister() { finder = new ColonDelimitedMovieFinder( movies.txt ); public List<Movie> moviesdirectedby(string arg) { List<Movie> movies = finder.findall(); for ( Iterator<Movie> it = movies.iterator(); it.hasnext(); ) { Movie movie = it.next(); if (!movie.getdirector().equals(arg) ) { it.remove(); return movies; 3

4 Problem How to remove MovieLister s dependency on ColonDelimitedMovieFinder? Difference to DocManager example: MovieLister needs only one MovieFinder instance (service) DocManager must be able to create many Document objects at will 4

5 Idea Have the dependency (service) be injected by the client Inversion of Control Hollywood Principle ( don t call us, we ll call you ) Please note: DI is first and foremost a design pattern that can be implemented by hand. DI is, however, often equated with DI frameworks, e.g. Spring DI, Google Guice. 5

6 Types of Dependency Injection There are 3 types of dependency injection: 1. constructor injection 2. setter injection 3. interface injection 6

7 Constructor Injection - //assuming that finder instance is threadsafe public class MovieLister { private final MovieFinder finder; public MovieLister(MovieFinder finder) { this.finder = finder; public List<Movie> moviesdirectedby(string arg) { List<Movie> movies = finder.findall(); for ( Iterator<Movie> it = movies.iterator(); it.hasnext(); ) { Movie movie = it.next(); if (!movie.getdirector().equals(arg) ) { it.remove(); return movies; Usage: MovieLister movielister = new MovieLister(new ColonDelimitedMovieFinder( movies.txt )); List<Movie> movies = movielister.moviesdirectedby( Quentin Tarantino ); 7

8 Setter Injection - //assuming that finder instance is threadsafe public class MovieLister { private MovieFinder finder; public MovieLister() { public void setfinder(moviefinder finder) { this.finder = finder; public List<Movie> moviesdirectedby(string arg) { List<Movie> movies = finder.findall(); for ( Iterator<Movie> it = movies.iterator(); it.hasnext(); ) { Movie movie = it.next(); if (!movie.getdirector().equals(arg) ) { it.remove(); return movies; Usage: MovieLister movielister = new MovieLister(); movielister.setfinder(new ColonDelimitedMovieFinder( movies.txt )); List<Movie> movies = movielister.moviesdirectedby( Quentin Tarantino ); 8

9 Interface Injection - Example Provider of MovieFinder interface also defines injection interface, e.g. : public interface MovieFinderInjector { void injectmoviefinder(moviefinder finder); Each class that needs to get a MovieFinder injected has to implement injector //assuming that finder instance is threadsafe public class MovieLister implements MovieFinderInjector { private MovieFinder finder; public MovieLister() public void injectmoviefinder(moviefinder finder) { this.finder = finder; public List<Movie> moviesdirectedby(string arg) { 9

10 Setter vs. Interface Injection Only difference between setter and interface injection: Whether interface provider defines companion injection interface that implementing class must use for injection, or not. 10

11 Interface Injection - Example Usage: MovieLister movielister = new MovieLister(); movielister.injectmoviefinder(new ColonDelimitedMovieFinder( movies.txt )); List<Movie> movies = movielister.moviesdirectedby( Quentin Tarantino ); 11

12 Dependency Injection Frameworks DI Frameworks separate out instantiation configuration, i.e. bindings from abstract interfaces to concrete types. Configuration usually either in XML or in Java with annotations Wide-spread DI Frameworks: Apache Spring DI Google Guice 12

13 Guice: Constructor //assuming that finder instance is threadsafe public class MovieLister { private final MovieFinder public MovieLister(MovieFinder finder) { this.finder = finder; public List<Movie> moviesdirectedby(string arg) { List<Movie> movies = finder.findall(); for ( Iterator<Movie> it = movies.iterator(); it.hasnext(); ) { Movie movie = it.next(); if (!movie.getdirector().equals(arg) ) { it.remove(); return movies; 13

14 Guice: Constructor annotation tells Guice to create and fill in appropriate MovieFinder instance when creating MovieLister instance. Works only if bound type (e.g. ColonDelimitedMovieFinder) has zero-args non-private constructor, or uses itself constructor injection 14

15 Guice: Constructor Injection public class ColonDelimitedMovieFinder implements MovieFinder { private final String public ColonDelimitedMovieFinder(@Named("FILE NAME") String filename) { this.filename = annotation needed for instance binding,.i.e. binding of a type to an instance of that type. 15

16 Guice: Modules Bindings are defined in modules, i.e. Java classes that inherit from com.google.inject.abstractmodule and whose configure method contains the bindings: public class MovieListerModule extends AbstractModule protected void configure() { bind(moviefinder.class).to(colondelimitedmoviefinder.class); bind(string.class).annotatedwith(names.named("file NAME")).toInstance("movies.txt"); 16

17 Guice: Instantiation Instances are created by creating a Guice injector that uses a previously defined module having the injector create the application object(s) Injector injector = Guice.createInjector(new MovieListerModule()); MovieLister lister = injector.getinstance(movielister.class); 17

18 Guice: Setter //assuming that finder instance is threadsafe public class MovieLister { private MovieFinder public void setfinder(moviefinder finder) { this.finder = finder; public List<Movie> moviesdirectedby(string arg) { List<Movie> movies = finder.findall(); for ( Iterator<Movie> it = movies.iterator(); it.hasnext(); ) { Movie movie = it.next(); if (!movie.getdirector().equals(arg) ) { it.remove(); return movies; 18

19 Guice: Setter Injection public class ColonDelimitedMovieFinder implements MovieFinder { private String public void setfilename(@named("file NAME") String filename) { this.filename = public List<Movie> findall() {... MovieListerModule remains the same as before, because mappings also remain the same. 19

20 Guice: Setter Injection Object instantiation can also remain the same Guice automatically calls setter methods to inject necessary dependencies. Injector injector = Guice.createInjector(new MovieListerModule()); MovieLister lister = injector.getinstance(movielister.class); Or, objects can be instantiated as usually, and then Guice can fill in dependencies using setter methods: Injector injector = Guice.createInjector(new MovieListerModule()); MovieLister lister = new MovieLister(); injector.injectmembers(lister); 20

21 Constructor vs. Setter Injection Constructor Injection only valid and complete objects are created better chances for immutability Setter Injection can lead to unnecessarily mutable objects injection through easy-to-read methods necessary if dependencies are not available at creation time, e.g. cyclic dependencies Recommendation: Use setter injection only if necessary. 21

22 DocManager Reloaded How to apply DI pattern to DocManager example? Inject concrete DocumentFactory as a service into DocManager So... if client knows when to create objects, but doesn t know (neither care) how, then... inject client with factory that can be used to get instances as needed. 22

23 DocManager // assuming that concrete Document is threadsafe public class DocManager { private final Collection<Document> docs; private final DocumentFactory public DocManager(DocumentFactory docfactory) { this.docfactory = docfactory; docs = new ConcurrentLinkedQueue<Document>(); public void createdoc() { Document doc = docfactory.newdocument(); docs.add(doc); doc.open(); public void opendocs() { for ( Document doc : docs ) doc.open(); 23

24 DocManager Reloaded Sample Bindings: public class DocManagerModule extends AbstractModule protected void configure() { bind(documentfactory.class).to(latexdocfactory.class); Usage: Injector injector = Guice.createInjector(new DocManagerModule()); DocManager docmanager = injector.getinstance(docmanager.class); 24

25 You Want More? Read more about DI in Martin Fowler s seminal online article 25

26 Service Locator 26

27 Motivation Back to Martin Fowler s DI //assuming that ColonDelimitedMovieFinder is threadsafe public class MovieLister { private final MovieFinder finder; public MovieLister() { finder = new ColonDelimitedMovieFinder( movies.txt ); public List<Movie> moviesdirectedby(string arg) { List<Movie> movies = finder.findall(); for ( Iterator<Movie> it = movies.iterator(); it.hasnext(); ) { Movie movie = it.next(); if (!movie.getdirector().equals(arg) ) { it.remove(); return movies; 27

28 Problem & Idea How to remove MovieLister s dependency on ColonDelimitedMovieFinder? Pass a service locator into MovieLister that can be queried for all kinds of services. 28

29 Example public interface ServiceLocator { MovieFinder getmoviefinder(string //assuming that ColonDelimitedMovieFinder is threadsafe public class MovieLister { private final MovieFinder finder; private final ServiceLocator servicelocator; public MovieLister(ServiceLocator servicelocator) { finder = servicelocator.getmoviefinder( movies.txt ); public List<Movie> moviesdirectedby(string arg) {... 29

30 But... (a) there s now a dependency on the service locator... yes, but only on one object for all services. (b) how does service locator get into MovieLister? e.g. with dependency injection. 30

31 Example Using Guice dependency //assuming that ColonDelimitedMovieFinder is threadsafe public class MovieLister { private final MovieFinder finder; private final ServiceLocator public MovieLister(ServiceLocator servicelocator) { finder = servicelocator.getmoviefinder( movies.txt ); public List<Movie> moviesdirectedby(string arg) {... 31

32 Service Locator vs. Abstract Factory both can create objects of different types (services vs. products) product types belong to a product family, services unrelated with each other abstract factory creates many instances of a product type, service locator only one instance per service type 32

33 Builder 33

34 Motivating Example (J. Bloch) Suppose a class NutritionFacts that describes food items. A few specifications are mandatory, many are public class NutritionFacts { private final int servingsize; // (ml) - mandatory private final int servings; // (per container) - mandatory private final int calories; // - optional private final int fat; // (g) - optional private final int sodium; // (mg) - optional private final int carbs; // (g) - optional... 34

35 Motivating Example (J. Bloch) Question: How to create instances of NutritionFacts? Option 1: telescoping constructors 35

36 Option 1 - Telescoping C public class NutritionFacts { private final int servingsize; // (ml) - mandatory private final int servings; // (per container) - mandatory private final int calories; // - optional private final int fat; // (g) - optional private final int sodium; // (mg) - optional private final int carbs; // (g) - optional public NutritionFacts(int servingsize, int servings) { this(servingsize, servings, 0); public NutritionFacts(int servingsize, int servings, int calories) { this(servingsize, servings, calories, 0); public NutritionFacts(int servingsize, int servings, int calories, int fat) { this(servingsize, servings, calories, fat, 0); 36

37 Option 1 - Telescoping C tors public NutritionFacts(int servingsize, int servings, int calories, int fat, int sodium) { this(servingsize, servings, calories, fat, sodium, 0); public NutritionFacts(int servingsize, int servings, int calories, int fat, int sodium, int carbs) { this.servingsize = servingsize; this.servings = servings; this.calories = calories; this.fat = fat; this.sodium = sodium; this.carbs = carbs; Sample usage: NutritionFacts cocacola = new NutritionFacts(240, 8, 100, 0, 35, 27); 37

38 Second Try... Question: How to create instances of NutritionFacts? Option 2: JavaBeans Pattern 38

39 Option 2 - JavaBeans Pattern public class NutritionFacts { private int servingsize = -1; // (ml) - mandatory private int servings = -1; // (per container) - mandatory private int calories = 0; // - optional private int fat = 0; // (g) - optional private int sodium = 0; // (mg) - optional private int carbs = 0; // (g) - optional public NutritionFacts() { public void setservingsize(int servingsize) { this.servingsize = servingsize; public void setservings(int servings) { this.servings = servings; public void setcalories(int calories) { this.calories = calories; 39

40 Option 2 - JavaBeans Pattern public void setfat(int fat) { this.fat = fat; public void setsodium(int sodium) { this.sodium = sodium; public void setcarbs(int carbs) { carbs = carbs; Sample usage: NutritionFacts cocacola = new NutritionFacts(); cocacola.setservingsize(240); cocacola.setservings(8); cocacola.setcalories(100); cocacola.setsodium(35); cocacola.setcarbs(27); 40

41 Third Try... Question: How to create instances of NutritionFacts? Option 3: constructor/setter combination 41

42 Option 3 - C tor & Setters public class NutritionFacts { private final int servingsize; // (ml) - mandatory private final int servings; // (per container) - mandatory private int calories = 0; // - optional private int fat = 0; // (g) - optional private int sodium = 0; // (mg) - optional private int carbs = 0; // (g) - optional public NutritionFacts(int servingsize, int servings) { this.servingsize = servingsize; this.servings = servings; public void setcalories(int calories) { this.calories = calories; public void setfat(int fat) { this.fat = fat; 42

43 Option 3 - C tor & Setters public void setsodium(int sodium) { this.sodium = sodium; public void setcarbs(int carbs) { carbs = carbs; Sample usage: NutritionFacts cocacola = new NutritionFacts(240, 8); cocacola.setcalories(100); cocacola.setsodium(35); cocacola.setcarbs(27); 43

44 Comparison Option 1 only valid and complete objects are created preserves immutability hard to read Option 2 creation of incomplete, invalid objects loss of immutability easy to read 44

45 Comparison Option 3 only valid and complete objects are created easy to read loss of immutability There is another option that combines the best of all three options! 45

46 Option 4 - Builder Idea: Define a builder that can be fed with a combination of NutritionFacts values, and then be used to create a NutritionFacts instance. Client NutritionFactsBuilder c'tor(servingsize, servings) setcalories(int calories) setfat(int Fat) setsodium(int sodium) setcarbs(int carbs) build() NutritionFacts c'tor(nutritionfactsbuilder) return new NutritionFacts(self); 46

47 Option 4 - public class NutritionFacts { private final int servingsize; // (ml) 47 - mandatory private final int servings; // (per container) - mandatory private final int calories; // - optional private final int fat; // (g) - optional private final int sodium; // (mg) - optional private final int carbs; // (g) - optional public static class Builder { private final int servingsize; private final int servings; // optional params initialized to default values private int calories = 0; private int fat = 0; private int sodium = 0; private int carbs = 0; public Builder(int servingsize, int servings) { this.servingsize = servingsize; this.servings = servings;

48 Option 4 - Builder public void setcalories(int calories) { this.calories = calories; public void setfat(int fat) { this.fat = fat; public void setsodium(int sodium) { this.sodium = sodium; public void setcarbs(int carbs) { this.carbs = carbs; public NutritionFacts build() { return new NutritionFacts(this); 48

49 Option 4 - Builder private NutritionFacts(Builder builder) { servingsize = builder.servingsize; servings = builder.servings; calories fat sodium carbs = builder.calories; = builder.fat; = builder.sodium; = builder.carbs; Sample Usage: NutritionFacts.Builder cocacolabuilder = new NutritionFacts.Builder(240, 8); cocacolabuilder.setcalories(100); cocacolabuilder.setsodium(35); cocacolabuilder.setcarbs(27); NutritionFacts cocacola = cocacolabuilder.build(); 49

50 Builder - Structure creates Builder instance, thereby passes in all mandatory params uses set operations to set optional params calls build operation to have Product instance created Client return new Product(self); Builder c'tor(<mandatory params>) setoptionalparam1() setoptionalparam2() build() provides c'tor that expects a Builder instance and copies all values into itself Product c'tor(builder) use() provides c tor with all mandatory params initializes optional params to default values provides set operation for each optional param provides build operation that calls Product s c tor, passes in reference to itself 50

51 Pros & Cons Pro: creates only valid products easy to read preserves immutability configured builder can be used to create more than one product Con: builder object = abstract factory more verbose implementation more verbose usage than telescoping c'tors additional object needed to create product additional runtime and memory cost 51

52 Creational Patterns Discussion 52

53 Overview Abstract Factory Service Locator Prototype Builder Dependency Injection Singleton Factory Method 53

54 Similarities & Commonalities Abstract Factory Service Locator Prototype Builder Dependency Injection Singleton Factory Method : patterns that use a dedicated object to create new objects A B : A can be used to feed B into client code 54

Section 9: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst

Section 9: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst Section 9: Design Patterns Slides by Alex Mariakakis with material from David Mailhot, Hal Perkins, Mike Ernst What Is A Design Pattern A standard solution to a common programming problem A technique for

More information

Section 8: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst

Section 8: Design Patterns. Slides by Alex Mariakakis. with material from David Mailhot, Hal Perkins, Mike Ernst Section 8: Design Patterns Slides by Alex Mariakakis with material from David Mailhot, Hal Perkins, Mike Ernst Announcements HW8 due tonight 10 pm Quiz 7 due tonight 10 pm Industry guest speaker tomorrow!

More information

Section 9: Design Patterns. Slides adapted from Alex Mariakakis, with material from David Mailhot, Hal Perkins, Mike Ernst

Section 9: Design Patterns. Slides adapted from Alex Mariakakis, with material from David Mailhot, Hal Perkins, Mike Ernst Section 9: Design Patterns Slides adapted from Alex Mariakakis, with material from David Mailhot, Hal Perkins, Mike Ernst Agenda What are design patterns? Creational patterns review Structural patterns

More information

Dependency Injection with Guice

Dependency Injection with Guice Author: Assaf Israel - Technion 2013 Dependency Injection with Guice Technion Institute of Technology 236700 1 Complex Dependency Injection Deep dependencies (with no default) A depends on B, which depends

More information

Dependency Injection. Kenneth M. Anderson University of Colorado, Boulder Lecture 30 CSCI 4448/ /08/11

Dependency Injection. Kenneth M. Anderson University of Colorado, Boulder Lecture 30 CSCI 4448/ /08/11 Dependency Injection Kenneth M. Anderson University of Colorado, Boulder Lecture 30 CSCI 4448/5448 12/08/11 1 Goals of the Lecture Introduce the topic of dependency injection See examples using the Spring

More information

AJAX und das Springframework

AJAX und das Springframework AJAX und das Springframework Peter Welkenbach Guido Schmutz Trivadis GmbH Basel Baden Bern Lausanne Zürich Düsseldorf Frankfurt/M. Freiburg i. Br. Hamburg München Stuttgart. Wien Lightweight Container

More information

Design Patterns. Introduction. Oliver Haase

Design Patterns. Introduction. Oliver Haase Design Patterns Introduction Oliver Haase An instrument, a tool, an utensil, whatsoever it be, if it be fit for the purpose it was made for, it is as it should be though he perchance that made and fitted

More information

Big Modular Java with Guice

Big Modular Java with Guice Big Modular Java with Guice Jesse Wilson Dhanji Prasanna May 28, 2009 Post your questions for this talk on Google Moderator: code.google.com/events/io/questions Click on the Tech Talks Q&A link. 2 How

More information

Design patterns using Spring and Guice

Design patterns using Spring and Guice Design patterns using Spring and Guice Dhanji R. Prasanna MANNING contents 1 Dependency 2 Time preface xv acknowledgments xvii about this book xix about the cover illustration xxii injection: what s all

More information

Copyright Descriptor Systems, Course materials may not be reproduced in whole or in part without prior written consent of Joel Barnum

Copyright Descriptor Systems, Course materials may not be reproduced in whole or in part without prior written consent of Joel Barnum Copyright Descriptor Systems, 2001-2010. Course materials may not be reproduced in whole or in part without prior written consent of Joel Barnum Copyright Descriptor Systems, 2001-2010. Course materials

More information

Comparing Spring & Guice

Comparing Spring & Guice Comparing Spring & Guice Bill Dudney Dudney.net Bill Dudney Comparing Spring & Guice Slide 1 Dependency Injection WarpSimulator capacitor : FluxCapacitor simulate() : void FluxCapacitor capacitate()

More information

Java Technologies. Lecture III. Valdas Rapševičius. Vilnius University Faculty of Mathematics and Informatics

Java Technologies. Lecture III. Valdas Rapševičius. Vilnius University Faculty of Mathematics and Informatics Preparation of the material was supported by the project Increasing Internationality in Study Programs of the Department of Computer Science II, project number VP1 2.2 ŠMM-07-K-02-070, funded by The European

More information

Dependency Injection & Design Principles Recap Reid Holmes

Dependency Injection & Design Principles Recap Reid Holmes Material and some slide content from: - Krzysztof Czarnecki - Ian Sommerville - Head First Design Patterns Dependency Injection & Design Principles Recap Reid Holmes REID HOLMES - SE2: SOFTWARE DESIGN

More information

Guice. Java DI Framework

Guice. Java DI Framework Guice Java DI Framework Agenda Intro to dependency injection Cross-cutting concerns and aspectoriented programming More Guice What is DI? Dependency injection is a design pattern that's like a "super factory".

More information

CS410J: Advanced Java Programming

CS410J: Advanced Java Programming CS410J: Advanced Java Programming The Dependency Injection design pattern decouples dependent objects so that they may be configured and tested independently. Google Guice manages dependencies among objects

More information

Dependency Injection & Design Principles Recap Reid Holmes

Dependency Injection & Design Principles Recap Reid Holmes Material and some slide content from: - Krzysztof Czarnecki - Ian Sommerville - Head First Design Patterns Dependency Injection & Design Principles Recap Reid Holmes REID HOLMES - SE2: SOFTWARE DESIGN

More information

Dependency Inversion, Dependency Injection and Inversion of Control. Dependency Inversion Principle by Robert Martin of Agile Fame

Dependency Inversion, Dependency Injection and Inversion of Control. Dependency Inversion Principle by Robert Martin of Agile Fame Dependency Inversion, Dependency Injection and Inversion of Control Dependency Inversion Principle by Robert Martin of Agile Fame Dependency Inversion Principle History Postulated by Robert C. Martin Described

More information

What is Dependency Injection (DI) and. Inversion of Control (IoC)?

What is Dependency Injection (DI) and. Inversion of Control (IoC)? Definitions What is DI? What is Dependency Injection (DI) and Part of IoC Inversion of Control (IoC)? object Injectors (Constructor, Setter or Interface) --- Dependencies object Pass object reference,

More information

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX Duration: 5 Days US Price: $2795 UK Price: 1,995 *Prices are subject to VAT CA Price: CDN$3,275 *Prices are subject

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently.

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently. Gang of Four Software Design Patterns with examples STRUCTURAL 1) Adapter Convert the interface of a class into another interface clients expect. It lets the classes work together that couldn't otherwise

More information

Designing for Modularity with Java 9

Designing for Modularity with Java 9 Designing for Modularity with Java 9 Paul Bakker @pbakker Sander Mak @Sander_Mak Today's journey Module primer Services & DI Modular design Layers & loading Designing for Modularity with Java 9 What if

More information

Singleton Pattern Creational

Singleton Pattern Creational Singleton Pattern Creational Intent» Ensure a class has only one instance» Provide a global point of access Motivation Some classes must only have one instance file system, window manager Applicability»

More information

Design Patterns. Structural Patterns. Oliver Haase

Design Patterns. Structural Patterns. Oliver Haase Design Patterns Structural Patterns Oliver Haase 1 Purpose Structural patterns describe how to compose classes (incl. interfaces) and objects to get larger structures. Class based structural patterns use

More information

Factory Method Pattern Creational. » Define an interface for creating an object but lets subclasses decide the specific class to instantiate

Factory Method Pattern Creational. » Define an interface for creating an object but lets subclasses decide the specific class to instantiate Factory Method Pattern Creational Intent» Define an interface for creating an object but lets subclasses decide the specific class to instantiate > Delegate creation to the appropriate subclass Also known

More information

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP OOP Object oriented programming Polymorphism Encapsulation Inheritance OOP Class concepts Classes can contain: Constants Delegates Events Fields Constructors Destructors Properties Methods Nested classes

More information

Software-Architecture Annotations, Reflection and Frameworks

Software-Architecture Annotations, Reflection and Frameworks Software-Architecture Annotations, Reflection and Frameworks Prof. Dr. Axel Böttcher 3. Oktober 2011 Objectives (Lernziele) Understand the Java feature Annotation Implement a simple annotation class Know

More information

Patterns and Best Practices for dynamic OSGi Applications

Patterns and Best Practices for dynamic OSGi Applications Patterns and Best Practices for dynamic OSGi Applications Kai Tödter, Siemens Corporate Technology Gerd Wütherich, Freelancer Martin Lippert, akquinet it-agile GmbH Agenda» Dynamic OSGi applications» Basics»

More information

Design Patterns. CSC207 Fall 2017

Design Patterns. CSC207 Fall 2017 Design Patterns CSC207 Fall 2017 Design Patterns A design pattern is a general description of the solution to a well-established problem using an arrangement of classes and objects. Patterns describe the

More information

Object Model. Object Oriented Programming Spring 2015

Object Model. Object Oriented Programming Spring 2015 Object Model Object Oriented Programming 236703 Spring 2015 Class Representation In Memory A class is an abstract entity, so why should it be represented in the runtime environment? Answer #1: Dynamic

More information

More on Design. CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson

More on Design. CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson More on Design CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson Outline Additional Design-Related Topics Design Patterns Singleton Strategy Model View Controller Design by

More information

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information

Apache Wink User Guide

Apache Wink User Guide Apache Wink User Guide Software Version: 0.1 The Apache Wink User Guide document is a broad scope document that provides detailed information about the Apache Wink 0.1 design and implementation. Apache

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

CS 520/620 Advanced Software Engineering Spring February 11, 2016

CS 520/620 Advanced Software Engineering Spring February 11, 2016 CS 520/620 Advanced Software Engineering Spring 2016 February 11, 2016 Recap How to recognize a bad design? How to come up with a good design? Separation of concerns. Consider expected extensions. Design

More information

5.1 Registration and Configuration

5.1 Registration and Configuration 5.1 Registration and Configuration Registration and Configuration Apache Wink provides several methods for registering resources and providers. This chapter describes registration methods and Wink configuration

More information

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring

More information

Software Design COSC 4353/6353 D R. R A J S I N G H

Software Design COSC 4353/6353 D R. R A J S I N G H Software Design COSC 4353/6353 D R. R A J S I N G H Creational Design Patterns What are creational design patterns? Types Examples Structure Effects Creational Patterns Design patterns that deal with object

More information

Design Patterns. CSC207 Winter 2017

Design Patterns. CSC207 Winter 2017 Design Patterns CSC207 Winter 2017 Design Patterns A design pattern is a general description of the solution to a well-established problem using an arrangement of classes and objects. Patterns describe

More information

The Strategy Pattern Design Principle: Design Principle: Design Principle:

The Strategy Pattern Design Principle: Design Principle: Design Principle: Strategy Pattern The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Design

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

SDC Design patterns GoF

SDC Design patterns GoF SDC Design patterns GoF Design Patterns The design pattern concept can be viewed as an abstraction of imitating useful parts of other software products. The design pattern is a description of communicating

More information

Further abstraction techniques

Further abstraction techniques Main concepts to be covered Further abstraction techniques Abstract classes and interfaces Abstract classes Interfaces Multiple inheritance 4.0 Simulations Programs regularly used to simulate real-world

More information

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable? Peer Instruction 8 Classes and Objects How can multiple methods within a Java class read and write the same variable? A. Allow one method to reference a local variable of the other B. Declare a variable

More information

The Singleton Pattern. Design Patterns In Java Bob Tarr

The Singleton Pattern. Design Patterns In Java Bob Tarr The Singleton Pattern Intent Ensure a class only has one instance, and provide a global point of access to it Motivation Sometimes we want just a single instance of a class to exist in the system For example,

More information

Design Pattern and Software Architecture: IV. Design Pattern

Design Pattern and Software Architecture: IV. Design Pattern Design Pattern and Software Architecture: IV. Design Pattern AG Softwaretechnik Raum E 3.165 Tele.. 60-3321 hg@upb.de IV. Design Pattern IV.1 Introduction IV.2 Example: WYSIWYG Editor Lexi IV.3 Creational

More information

JAVA SYLLABUS FOR 6 MONTHS

JAVA SYLLABUS FOR 6 MONTHS JAVA SYLLABUS FOR 6 MONTHS Java 6-Months INTRODUCTION TO JAVA Features of Java Java Virtual Machine Comparison of C, C++, and Java Java Versions and its domain areas Life cycle of Java program Writing

More information

CS 520/620 Advanced Software Engineering Fall September 27, 2016

CS 520/620 Advanced Software Engineering Fall September 27, 2016 CS 520/620 Advanced Software Engineering Fall 2016 September 27, 2016 Recap Behavioral patterns Strategy pattern Observer Iterator MVC revisited Design patterns commonly used in an MVC architecture Recap:

More information

Chris Donnan & Solomon Duskis

Chris Donnan & Solomon Duskis The Peer Frameworks Series -.Net and Java Spring Framework Developer Session Chris Donnan & Solomon Duskis All Rights Reserved 0 Overview 600-630 Light Snack 630 700 Introduction to Inversion of Control,

More information

The Singleton Pattern. Design Patterns In Java Bob Tarr

The Singleton Pattern. Design Patterns In Java Bob Tarr The Singleton Pattern Intent Ensure a class only has one instance, and provide a global point of access to it Motivation Sometimes we want just a single instance of a class to exist in the system For example,

More information

Chapter 13. Hibernate with Spring

Chapter 13. Hibernate with Spring Chapter 13. Hibernate with Spring What Is Spring? Writing a Data Access Object (DAO) Creating an Application Context Putting It All Together 1 / 24 What is Spring? The Spring Framework is an Inversion

More information

Assignment 5: Design Patterns

Assignment 5: Design Patterns Assignment 5: Design Patterns Exercise 1 Examine the listed Java APIs (see e.g. https://docs.oracle.com/javase/7/docs/api/ for more information) and identify some of the design patterns present. For each

More information

Cloning Enums. Cloning and Enums BIU OOP

Cloning Enums. Cloning and Enums BIU OOP Table of contents 1 Cloning 2 Integer representation Object representation Java Enum Cloning Objective We have an object and we need to make a copy of it. We need to choose if we want a shallow copy or

More information

Dependency Injection with ObjectPoolManager

Dependency Injection with ObjectPoolManager Dependency Injection with ObjectPoolManager Recently I got my hands over some of the IOC tools available for.net and really liked the concept of dependency injection from starting stage of application

More information

CHAPTER 6: CREATIONAL DESIGN PATTERNS

CHAPTER 6: CREATIONAL DESIGN PATTERNS CHAPTER 6: CREATIONAL DESIGN PATTERNS SESSION III: BUILDER, PROTOTYPE, SINGLETON Software Engineering Design: Theory and Practice by Carlos E. Otero Slides copyright 2012 by Carlos E. Otero For non-profit

More information

Design Patterns. Decorator. Oliver Haase

Design Patterns. Decorator. Oliver Haase Design Patterns Decorator Oliver Haase 1 Motivation Your task is to program a coffee machine. The machine brews plain coffee, coffee with cream, sugar, sweetener, and cinnamon. A plain coffee costs 0,90,

More information

A few important patterns and their connections

A few important patterns and their connections A few important patterns and their connections Perdita Stevens School of Informatics University of Edinburgh Plan Singleton Factory method Facade and how they are connected. You should understand how to

More information

Plan. A few important patterns and their connections. Singleton. Singleton: class diagram. Singleton Factory method Facade

Plan. A few important patterns and their connections. Singleton. Singleton: class diagram. Singleton Factory method Facade Plan A few important patterns and their connections Perdita Stevens School of Informatics University of Edinburgh Singleton Factory method Facade and how they are connected. You should understand how to

More information

Design Pattern- Creational pattern 2015

Design Pattern- Creational pattern 2015 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

More information

Lecture 13: Design Patterns

Lecture 13: Design Patterns 1 Lecture 13: Design Patterns Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2005 2 Pattern Resources Pattern Languages of Programming Technical conference on Patterns

More information

Pattern Resources. Lecture 25: Design Patterns. What are Patterns? Design Patterns. Pattern Languages of Programming. The Portland Pattern Repository

Pattern Resources. Lecture 25: Design Patterns. What are Patterns? Design Patterns. Pattern Languages of Programming. The Portland Pattern Repository Pattern Resources Lecture 25: Design Patterns Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2003 Pattern Languages of Programming Technical conference on Patterns

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

Sitesbay.com. A Perfect Place for All Tutorials Resources. Java Projects C C++ DS Interview Questions JavaScript

Sitesbay.com.  A Perfect Place for All Tutorials Resources. Java Projects C C++ DS Interview Questions JavaScript Sitesbay.com A Perfect Place for All Tutorials Resources Java Projects C C++ DS Interview Questions JavaScript Core Java Servlet JSP JDBC Struts Hibernate Spring Java Projects C C++ DS Interview Questions

More information

Assignment 5: Design Patterns Spring 2015 (solution)

Assignment 5: Design Patterns Spring 2015 (solution) Assignment 5: Design Patterns Spring 2015 (solution) Exercise 1 Mostly taken from BalusC answer at http://stackoverflow.com/questions/ 1673841/examples-of-gof-design-patterns Creational (abstract factory,

More information

Appendix: Assorted Sweets

Appendix: Assorted Sweets Appendix: Assorted Sweets You re probably looking at this page right now because I referred you to it earlier in this book. While writing, I had to decide which examples fit in this book and which don

More information

Tapestry. Code less, deliver more. Rayland Jeans

Tapestry. Code less, deliver more. Rayland Jeans Tapestry Code less, deliver more. Rayland Jeans What is Apache Tapestry? Apache Tapestry is an open-source framework designed to create scalable web applications in Java. Tapestry allows developers to

More information

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017 Inheritance and Inheritance and Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek February 10, 2017 /FHTenL Inheritance and February 10, 2017 1/45 Topics

More information

Кирилл Розов Android Developer

Кирилл Розов Android Developer Кирилл Розов Android Developer Dependency Injection Inversion of Control (IoC) is a design principle in which custom-written portions of a computer program receive the flow of control from a generic framework

More information

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1 CS250 Intro to CS II Spring 2017 CS250 - Intro to CS II 1 Topics Virtual Functions Pure Virtual Functions Abstract Classes Concrete Classes Binding Time, Static Binding, Dynamic Binding Overriding vs Redefining

More information

TDDB84 Design Patterns Lecture 05. Builder, Singleton, Proxy. pelab

TDDB84 Design Patterns Lecture 05. Builder, Singleton, Proxy. pelab Lecture 05 Builder, Singleton, Proxy Peter Bunus Dept of Computer and Information Science Linköping University, Sweden petbu@ida.liu.se The Constitution of Software Architects Encapsulate what varies.

More information

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods

More information

Apache Wink 0.1 Feature Set

Apache Wink 0.1 Feature Set Apache Wink 0.1 Feature Set Software Version: 0.1 [The Wink REST Runtime Feature Set internal draft document is a broad scope document that provides detailed information about the Runtime strategy and

More information

Web Application Development Using Spring, Hibernate and JPA

Web Application Development Using Spring, Hibernate and JPA Web Application Development Using Spring, Hibernate and JPA Duration: 5 Days US Price: $2795 UK Price: 1,995 *Prices are subject to VAT CA Price: CDN$3,275 *Prices are subject to GST/HST Delivery Options:

More information

CSE 219 COMPUTER SCIENCE III STRUCTURAL DESIGN PATTERNS SLIDES COURTESY: RICHARD MCKENNA, STONY BROOK UNIVERSITY.

CSE 219 COMPUTER SCIENCE III STRUCTURAL DESIGN PATTERNS SLIDES COURTESY: RICHARD MCKENNA, STONY BROOK UNIVERSITY. CSE 219 COMPUTER SCIENCE III STRUCTURAL DESIGN PATTERNS SLIDES COURTESY: RICHARD MCKENNA, STONY BROOK UNIVERSITY. Common Design Patterns Creational Structural Behavioral Factory Singleton Builder Prototype

More information

Web Application Development Using Spring, Hibernate and JPA

Web Application Development Using Spring, Hibernate and JPA Web Application Development Using Spring, Hibernate and JPA Duration: 5 Days Price: 1,995 + VAT Course Description: This course provides a comprehensive introduction to JPA (the Java Persistence API),

More information

Metadata driven component development. using Beanlet

Metadata driven component development. using Beanlet Metadata driven component development using Beanlet What is metadata driven component development? It s all about POJOs and IoC Use Plain Old Java Objects to focus on business logic, and business logic

More information

Dependency Injection and Spring. INF5750/ Lecture 2 (Part II)

Dependency Injection and Spring. INF5750/ Lecture 2 (Part II) Dependency Injection and Spring INF5750/9750 - Lecture 2 (Part II) Problem area Large software contains huge number of classes that work together How to wire classes together? With a kind of loose coupling,

More information

Programming in Scala Second Edition

Programming in Scala Second Edition Programming in Scala Second Edition Martin Odersky, Lex Spoon, Bill Venners artima ARTIMA PRESS WALNUT CREEK, CALIFORNIA Contents Contents List of Figures List of Tables List of Listings Foreword Foreword

More information

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

Annotation Hammer Venkat Subramaniam (Also published at

Annotation Hammer Venkat Subramaniam (Also published at Annotation Hammer Venkat Subramaniam venkats@agiledeveloper.com (Also published at http://www.infoq.com) Abstract Annotations in Java 5 provide a very powerful metadata mechanism. Yet, like anything else,

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Lecture 7: Data Abstractions

Lecture 7: Data Abstractions Lecture 7: Data Abstractions Abstract Data Types Data Abstractions How to define them Implementation issues Abstraction functions and invariants Adequacy (and some requirements analysis) Towards Object

More information

com Spring + Spring-MVC + Spring-Boot + Design Pattern + XML + JMS Hibernate + Struts + Web Services = 8000/-

com Spring + Spring-MVC + Spring-Boot + Design Pattern + XML + JMS Hibernate + Struts + Web Services = 8000/- www.javabykiran. com 8888809416 8888558802 Spring + Spring-MVC + Spring-Boot + Design Pattern + XML + JMS Hibernate + Struts + Web Services = 8000/- Java by Kiran J2EE SYLLABUS Servlet JSP XML Servlet

More information

Services in Joomla 4. Allon Moritz J and Beyond 13. May 2018

Services in Joomla 4. Allon Moritz J and Beyond 13. May 2018 Services in Joomla 4 Allon Moritz J and Beyond 13. May 2018 About Me Allon Moritz @digitpeak / @laoneo Founder Digital Peak GmbH Doing Joomla extensions since 2007 Joomla 4 Working group Team Lead Media

More information

20 Most Important Java Programming Interview Questions. Powered by

20 Most Important Java Programming Interview Questions. Powered by 20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by

More information

Atelier Java - J2. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Atelier Java - J2. Marwan Burelle.   EPITA Première Année Cycle Ingénieur. marwan.burelle@lse.epita.fr http://wiki-prog.kh405.net Plan 1 2 Plan 1 2 Notions of interfaces describe what an object must provide without describing how. It extends the types name strategy to provide

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Pieter van den Hombergh Stefan Sobek. April 18, 2018

Pieter van den Hombergh Stefan Sobek. April 18, 2018 Pieter van den Hombergh Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek April 18, 2018 /FHTenL April 18, 2018 1/13 To mock or not to mock In many cases, a class (system under test or SUT) does

More information

Service Oriented Computing: XML Binding and Spring remoting. Dr. Cristian Mateos Diaz ( ISISTAN - CONICET

Service Oriented Computing: XML Binding and Spring remoting. Dr. Cristian Mateos Diaz (  ISISTAN - CONICET Service Oriented Computing: XML Binding and Spring remoting Dr. Cristian Mateos Diaz (http://users.exa.unicen.edu.ar/~cmateos/cos) ISISTAN - CONICET Consuming Web Services: XML data binding Client Web

More information

Page 1

Page 1 Java 1. Core java a. Core Java Programming Introduction of Java Introduction to Java; features of Java Comparison with C and C++ Download and install JDK/JRE (Environment variables set up) The JDK Directory

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Object Model. Object Oriented Programming Winter

Object Model. Object Oriented Programming Winter Object Model Object Oriented Programming 236703 Winter 2014-5 Class Representation In Memory A class is an abstract entity, so why should it be represented in the runtime environment? Answer #1: Dynamic

More information

CS152: Programming Languages. Lecture 24 Bounded Polymorphism; Classless OOP. Dan Grossman Spring 2011

CS152: Programming Languages. Lecture 24 Bounded Polymorphism; Classless OOP. Dan Grossman Spring 2011 CS152: Programming Languages Lecture 24 Bounded Polymorphism; Classless OOP Dan Grossman Spring 2011 Revenge of Type Variables Sorted lists in ML (partial): type a slist make : ( a -> a -> int) -> a slist

More information

Inheritance and Testing Spring 2018 Exam Prep 4: February 11, 2019

Inheritance and Testing Spring 2018 Exam Prep 4: February 11, 2019 CS 61B Inheritance and Testing Spring 2018 Exam Prep 4: February 11, 2019 1 Playing with Puppers Suppose we have the Dog and Corgi classes which are a defined below with a few methods but no implementation

More information

Further abstraction techniques

Further abstraction techniques Objects First With Java A Practical Introduction Using BlueJ Further abstraction techniques Abstract classes and interfaces 2.0 Main concepts to be covered Abstract classes Interfaces Multiple inheritance

More information

Web Application Development Using Spring, Hibernate and JPA

Web Application Development Using Spring, Hibernate and JPA Web Application Development Using Spring, Hibernate and JPA Duration: 5 Days Price: CDN$3275 *Prices are subject to GST/HST Course Description: This course provides a comprehensive introduction to JPA

More information

USAL1J: Java Collections. S. Rosmorduc

USAL1J: Java Collections. S. Rosmorduc USAL1J: Java Collections S. Rosmorduc 1 A simple collection: ArrayList A list, implemented as an Array ArrayList l= new ArrayList() l.add(x): adds x at the end of the list l.add(i,x):

More information

CSE wi Final Exam 3/12/18. Name UW ID#

CSE wi Final Exam 3/12/18. Name UW ID# Name UW ID# There are 13 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

More information

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 9 Robert Grimm, New York University 1 Review Last week Modules 2 Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic

More information