Computer Science 209 The Singleton Pattern.

Slides:



Advertisements
Similar presentations
Chapter 5 Implementing a simple class. This chapter discusses n Implementing class definitions. n How to store data in an object and how to write method.
Advertisements

Computer Science 209 The Singleton Pattern. Random Numbers System.out.println((int)(Math.random() * 6) + 1); Math.random() uses a single generator that.
Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view class.
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Computer Science 209 Images and GUIs. Working with Java Colors The class java.awt.Color includes constants, such as Color.red, for some commonly used.
Computer Science 209 Applets. Applications and Applets A Java application runs on a stand-alone computer and may connect to other computers via sockets.
Introduction To Design Patterns You will learn about design techniques that have been successfully applied to different scenarios.
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
More design patterns The ADAPTER Pattern Actions and the COMMAND Pattern Actions and the COMMAND Pattern The FACTORY METHOD Pattern The PROXY Pattern The.
Chapter 8 Objects & Classes. Definition of Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) uses the analogy of real objects as a template.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Black Jack MVC By Jeremy DiPaolo. Introduction Goal: To create a Black Jack game that takes advantage of the MVC framework. Uses many of the components.
A Semantic Error in Google last weekend! Someone in Google typed an extra ‘/’ character into their URL List Link to CNN video report posted on Collab.
James Tam Introduction To Design Patterns You will learn about design techniques that have been successfully applied to different scenarios.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
DiceRoller DiceRoller (object class) and DiceRollerViewer client class: Write a DiceRoller class (similar to Yahtzee) to: Allow the person to initially.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
Chapter 7 Arrays. A 12-element array Declaring and Creating Arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[]
Singleton and Basic UML CS340100, NTHU Yoshi. What is UML Unified Modeling Language A standardized general-purpose modeling language in the field of software.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
Liang, Introduction to Java Programming, Sixth Edition1 Objects and Classes Gang Qian Department of Computer Science University of Central Oklahoma.
Computer Science 209 GUIs Model/View/Controller Layouts.
SEEM Java – Basic Introduction, Classes and Objects.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
Applets Java code is compiled into byte code instead of machine language –Languages like C, C++, Pascal and others are compiled into machine language so.
PROBABILITY What is the probability of flipping a head? There is a 1 in 2 chance – ½ = 0.5.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
Lecture 3: Introduction to Object and Classes
GUIs Model/View/Controller Layouts
Design Patterns C++ Java C#.
Writing Classes We have talked about classes and objects.
Inheritance and Polymorphism
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Sequences, Series, and Probability
Design Patterns C++ Java C#.
Chapter 5 Black Jack.
Introduction To Design Patterns
Singleton Pattern Command Pattern
Section 2 – CSE341 Patrick Larson, Spring 2013.
Object-Oriented Programming & Design Lecture 14 Martin van Bommel
Interfaces I once attended a Java user group meeting where James Gosling (Java's inventor) was the featured speaker. During the memorable Q&A session,
Class Constructor Recall: we can give default values to instance variables of a class The “numberOfPlayers” variable from the “PlayerData” class before.
The Math class The java.lang.Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square.
Section 2 – CSE341 Konstantin Weitz.
Nicholas Shahan Spring 2016
CSE 341 Section 2 Winter 2018 Adapted from slides by Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman.
What is Singleton Category: Creational pattern
Singleton design pattern
CSE 341 PL Section 2 Justin Harjanto.
More About Objects and Methods
Remote method invocation (RMI)
Spencer Pearson Spring 2017
CSE 341 Section 2 Nick Mooney Spring 2017
CS 350 – Software Design Singleton – Chapter 21
The Random Class The Random class is part of the java.util package
Implementing a simple class
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Section 12.2 Theoretical Probability
Chapter 9 Objects and Classes
Section 12.2 Theoretical Probability
Introduction To Design Patterns
OO Programming Concepts
Computer Science 209 Images and GUIs.
Introduction To Design Patterns
What to expect this week
Section 12.2 Theoretical Probability
CSC 205 Java Programming II
CS 151: Object-Oriented Design October 8 Class Meeting
Presentation transcript:

Computer Science 209 The Singleton Pattern

Random Numbers System.out.println((int)(Math.random() * 6) + 1); Math.random() uses a single generator that is seeded at the startup of the JVM. The seed is calculated as a function of the computer’s clock Kind of a pain to use to obtain random integers

java.util.Random The Random class is much more convenient to use java.util.Random generator = new java.util.Random(); System.out.println(generator.nextInt(6) + 1); System.out.println(generator.nextDouble()); System.out.println(generator.nextBoolean()); The Random class is much more convenient to use A Random object is also seeded from the clock

java.util.Random java.util.Random generator1 = new java.util.Random(); java.util.Random generator2 = new java.util.Random(); System.out.println(generator1.nextInt(6) + 1); System.out.println(generator2.nextInt(6) + 1); If distinct Random objects are seeded during the same millisecond, they will get the same seed and generate the same pseudo-random sequence

Rolling a Die import java.util.Random; public class Die{ private int value; private Random generator; public Die(){ value = 0; generator = new Random(); } public void roll(){ value = generator.nextInt(6) + 1; public String toString(){ return "" + value;

Rolling a Die private Die die1 = new Die(); public DiceApp(){ setTitle("Roll the Dice"); diceField1.setEditable(false); diceField2.setEditable(false); rollButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ die1.roll(); die2.roll(); diceField1.setText(die1.toString()); diceField2.setText(die2.toString()); } }); Container c = getContentPane(); JPanel panel = new JPanel(); panel.add(diceField1); panel.add(diceField2); c.add("Center", panel); c.add("South", rollButton);

Two Won’t Work The two dice are created within a millisecond of each other, so their random number generators produce the same sequence of numbers We need a way of sharing one instance of Random among all dice

The Context of the Singleton Pattern All clients need to share a single instance of a class No additional instances can be created accidentally

Solution of the Singleton Pattern Define a class with a private constructor The class constructs a single instance of itself The class includes a static method to return the single instance

A Better Random import java.util.Random; public class SingleRandom{ private static SingleRandom instance = new SingleRandom(); private Random generator; private SingleRandom(){ generator = new Random(); } public int nextInt(int limit){ return generator.nextInt(limit); public static SingleRandom getInstance(){ return instance;

A Better Die public class BetterDie{ private int value; private SingleRandom generator; public BetterDie(){ value = 0; generator = SingleRandom.getInstance(); } public void roll(){ value = generator.nextInt(6) + 1; public String toString(){ return "" + value;

Playing Cards Suits are strings, but should not be just any strings import javax.swing.*; public class Card implementsComparable<Card>{ private String suit; private int rank; public Card(String suit, int rank){ this.suit = suit; this.rank = rank; } Suits are strings, but should not be just any strings Must check and throw exceptions to enforce proper use Card queenOfSpades = new Card("spades", 12); Card twoOfHearts = new Card("hearts", 2);

Define a New Type for Suits import javax.swing.*; public class Card implementsComparable<Card>{ private Suit suit; private int rank; public Card(Suit suit, int rank){ this.suit = suit; this.rank = rank; } The type Suit is restricted to just 4 values The compiler enforces their proper use Card queenOfSpades = new Card(Suit.spade, 12); Card twoOfHearts = new Card(Suit.heart, 2);

Similar to the singleton, but has 4 instances public class Suit implements Comparable<Suit>{ static public final Suit spade = new Suit(4, "spades"); static public final Suit heart = new Suit(3, "hearts"); static public final Suit diamond = new Suit(2, "diamonds"); static public final Suit club = new Suit(1, "clubs"); private int order; private String name; private Suit(int ord, String nm){ name = nm; order = ord; } public int compareTo(Suit other){ return order - other.order; public String toString(){ return name; Similar to the singleton, but has 4 instances

Problem with Decks of Cards Every time you create a new deck, the card images must be reloaded from disk If you do this in an applet, they’re reloaded from a remote Web server Decks are mutable, but cards are not

Solution: 52 Singleton Cards The Card class maintains a static list of all cards, which are instantiated just once, when the first card is instantiated When new decks are instantiated, they receive references to cards in this list Card queenOfSpades = Card.newInstance(Suit.spade, 12); Card twoOfHearts = Card.newInstance(Suit.heart, 2);