Mixing Static and Non-static

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Advertisements

Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
Factory Design Pattern, cont’d COMP 401 Fall 2014 Lecture 13 10/2/2014.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
MIT AITI 2003 Lecture 7 Class and Object - Part I.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Effective Java: Generics Last Updated: Spring 2009.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Not overriding equals  what happens if you do not override equals for a value type class?  all of the Java collections will fail in confusing ways 1.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Utilities (Part 2) Implementing static features 1.
Chapter 18 Java Collections Framework
Java Objects and Classes. Overview n Creating objects that belong to the classes in the standard Java library n Creating your own classes.
Centre for Computer Technology ICT214 Object Oriented Design and Programming Week 02 – Classes, Objects, Instances Richard Salomon and Umesh Patel Centre.
Case study Students. Array of objects Arrays can hold objects (ref to objects!) Each cell in an array of objects is null by default Sample: from student.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Defining Classes II. Today’s topics  Static methods  Static variables  Wrapper classes  References  Class parameters  Copy constructor.
CSC 142 Computer Science II Zhen Jiang West Chester University
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Goals for Today 1  Multiton  maps  static factory methods.
Exceptions, cont’d. Factory Design Pattern COMP 401 Fall 2014 Lecture 12 9/30/2014.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
Classes and Objects CS177 Rec 10. Announcements Project 4 is posted ◦ Milestone due on Nov. 12. ◦ Final submission due on Nov. 19. Exam 2 on Nov. 4 ◦
Puzzle 1  what does the following program print? public class Puzzle01 { public static void main(String[] args) { System.out.print("C" + "S" + "E"); System.out.println('1'
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Composition 1.  recall that an object of type X that is composed of an object of type Y means  X has-a Y object and  X owns the Y object  in other.
Mixing Static and Non-static Singleton 1. Singleton Pattern 2  “There can be only one.”  Connor MacLeod, Highlander.
Maps Nick Mouriski.
Iteration Abstraction SWE Software Construction Fall 2009.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
CPSC 252 Tables / Maps / Dictionaries Page 1 Tables, Maps and Dictionaries A table (or map or dictionary) is a collection of key/value pairs. In general.
More constructors 1. Constructors  recall that a public constructor is what a client uses to create an object  the purpose of a constructor is to initialize.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
CompareTo.
Containers and Lists CIS 40 – Introduction to Programming in Python
Intro To Classes Review
Information hiding.
The hashCode method.
Building Java Programs
CIS 199 Final Review.
Implementing static features
slides created by Ethan Apter and Marty Stepp
Review for Midterm 3.
Presentation transcript:

Mixing Static and Non-static Multiton

Goals for Today Multiton review maps static factory methods

Singleton UML Class Diagram - INSTANCE : Singleton ... - Singleton() + getInstance() : Singleton

One Instance per State the Java language specification guarantees that identical String literals are not duplicated prints: same object? true the compiler ensures that identical String literals all refer to the same object a single instance per unique state // client code somewhere String s1 = "xyz"; String s2 = "xyz"; // how many String instances are there? System.out.println("same object? " + (s1 == s2) ); [notes 3.5]

Multiton a singleton class manages a single instance of the class a multiton class manages multiple instances of the class what do you need to manage multiple instances? a collection of some sort how does the client request an instance with a particular state? it needs to pass the desired state as arguments to a method

Singleton vs Multiton UML Diagram - INSTANCE : Singleton ... - Singleton() + getInstance() : Singleton Multiton - instances : Map ... - Multiton() + getInstance(Object) : Multiton

Singleton vs Multiton Singleton one instance zero-parameter accessor private static final Santa INSTANCE = new Santa(); zero-parameter accessor public static Santa getInstance()

Singleton vs Multiton Multiton multiple instances (each with unique state) private static final Map<String, PhoneNumber> instances = new TreeMap<String, PhoneNumber>(); accessor needs to provide state information public static PhoneNumber getInstance(int areaCode, int exchangeCode, int stationCode)

Map<String, PhoneNumber> a map stores key-value pairs Map<String, PhoneNumber> values are put into the map using the key key type value type // client code somewhere Map<String, PhoneNumber> m = new TreeMap<String, PhoneNumber>; PhoneNumber ago = new PhoneNumber(416, 979, 6648); String key = "4169796648" m.put(key, ago); [AJ 16.2]

values can be retrieved from the map using only the key if the key is not in the map the value returned is null // client code somewhere Map<String, PhoneNumber> m = new TreeMap<String, PhoneNumber>; PhoneNumber ago = new PhoneNumber(416, 979, 6648); String key = "4169796648"; m.put(key, ago); PhoneNumber gallery = m.get(key); // == ago PhoneNumber art = m.get("4169796648"); // == ago PhoneNumber pizza = m.get("4169671111"); // == null

a map is not allowed to hold duplicate keys if you re-use a key to insert a new object, the existing object corresponding to the key is removed and the new object inserted // client code somewhere Map<String, PhoneNumber> m = new TreeMap<String, PhoneNumber>; PhoneNumber ago = new PhoneNumber(416, 979, 6648); String key = "4169796648"; m.put(key, ago); // add ago System.out.println(m); m.put(key, new PhoneNumber(905, 760, 1911)); // replaces ago prints {4169796648=(416) 979-6648} {4169796648=(905) 760-1911}

Mutable Keys from http://docs.oracle.com/javase/7/docs/api/java/util/Map.html Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.

public class MutableKey { public static void main(String[] args) Map<Date, String> m = new TreeMap<Date, String>(); Date d1 = new Date(100, 0, 1); Date d2 = new Date(100, 0, 2); Date d3 = new Date(100, 0, 3); m.put(d1, "Jan 1, 2000"); m.put(d2, "Jan 2, 2000"); m.put(d3, "Jan 3, 2000"); d2.setYear(101); // mutator System.out.println("d1 " + m.get(d1)); // d1 Jan 1, 2000 System.out.println("d2 " + m.get(d2)); // d2 Jan 2, 2000 System.out.println("d3 " + m.get(d3)); // d3 null } don't mutate keys; bad things will happen change TreeMap to HashMap and see what happens

Making PhoneNumber a Multiton multiple instances (each with unique state) private static final Map<String, PhoneNumber> instances = new TreeMap<String, PhoneNumber>(); accessor needs to provide state information public static PhoneNumber getInstance(int areaCode, int exchangeCode, int stationCode) getInstance() will get an instance from instances if the instance is in the map; otherwise, it will create the new instance and put it in the map

Making PhoneNumber a Multiton require private constructors to prevent clients from creating instances on their own clients should use getInstance() require immutability of PhoneNumbers to prevent clients from modifying state, thus making the keys inconsistent with the PhoneNumbers stored in the map recall the recipe for immutability...

public class PhoneNumber implements Comparable<PhoneNumber> { private static final Map<String, PhoneNumber> instances = new TreeMap<String, PhoneNumber>(); private final short areaCode; private final short exchangeCode; private final short stationCode; private PhoneNumber(int areaCode, int exchangeCode, int stationCode) { // identical to previous versions }

public static PhoneNumber getInstance(int areaCode, int exchangeCode, int stationCode) { String key = "" + areaCode + exchangeCode + stationCode; PhoneNumber n = PhoneNumber.instances.get(key); if (n == null) n = new PhoneNumber(areaCode, exchangeCode, stationCode); PhoneNumber.instances.put(key, n); } return n; // remainder of PhoneNumber class ... why is validation not needed?

public class PhoneNumberClient { public static void main(String[] args) { PhoneNumber x = PhoneNumber.getInstance(416, 736, 2100); PhoneNumber y = PhoneNumber.getInstance(416, 736, 2100); PhoneNumber z = PhoneNumber.getInstance(905, 867, 5309); System.out.println("x equals y: " + x.equals(y) + " and x == y: " + (x == y)); System.out.println("x equals z: " + x.equals(z) + " and x == z: " + (x == z)); } x equals y: true and x == y: true x equals z: false and x == z: false

Bonus Content notice that Singleton and Multiton use a static method to return an instance of a class a static method that returns an instance of a class is called a static factory method factory because, as far as the client is concerned, the method creates an instance similar to a constructor

Static Factory Methods many examples java.lang.Integer public static Integer valueOf(int i) Returns a Integer instance representing the specified int value. java.util.Arrays public static int[] copyOf(int[] original, int newLength) Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

Java API Static Factory Methods java.lang.String public static String format(String format, Object... args) Returns a formatted string using the specified format string and arguments. cse1030.Complex public static Complex valueOf(String s) Returns a complex number holding the value represented by the given string.

you can give meaningful names to static factory methods (unlike constructors) public class Person { private String name; private int age; private int weight; public Person(String name, int age, int weight) { // ... } public Person(String name, int age) { // ... } public Person(String name, int weight) { // ... } // ... } illegal overload: same signature

public class Person { // modified from PEx's // attributes public class Person { // modified from PEx's // attributes ... public Person(String name, int age, int weight) { // ... } public static Person withAge(String name, int age) { return new Person(name, age, DEFAULT_WEIGHT); } public static Person withWeight(String name, int weight) { return new Person(name, DEFAULT_AGE, weight);

A Singleton Puzzle: What is Printed? public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR); private Elvis() { this.beltSize = CURRENT_YEAR – 1930; } public int getBeltSize() { return this.beltSize; } public static void main(String[] args) { System.out.println("Elvis has a belt size of " + INSTANCE.getBeltSize()); } from Java Puzzlers by Joshua Bloch and Neal Gafter