Computer Science 209 The Singleton Pattern. Random Numbers System.out.println((int)(Math.random() * 6) + 1); Math.random() uses a single generator that.

Slides:



Advertisements
Similar presentations
The Random Class.
Advertisements

JSP and Servelets.
The ArrayList Class and the enum Keyword
1 CSE 331 Enumerated types ( enum ) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view class.
1 Todays Objectives Announcements Homework #1 is due next week Return Quiz 1 – answers are posted on the Yahoo discussion page site Basic Java Programming.
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.
1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
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.
Basic Java – Interface design. Understand: How to use TextPad for Java How to define classes and objects How to create a GUI interface How event-driven.
The Point Class public class Point { public double x; public double y; public Point(double x0, double y0) { x = x0; y = y0; } public double distance(Point.
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Java Programming Abstract classes and Interfaces.
Craps. /* * file : Craps.java * file : Craps.java * author: george j. grevera, ph.d. * author: george j. grevera, ph.d. * desc. : program to simulate.
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
The Model-View Approach in Java. OK, you’ve got “Hello World” running... What now?
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Bar Graph Design. Left-side/Right-side mechanical processing creative, abstract reasoning.
1 Chapter 8 Objects and Classes Lecture 2 Prepared by Muhanad Alkhalisy.
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
EXAMPLES. Example 1: Write a Java method that performs addition on two binary numbers. Each binary number is kept in an integer array
Building Java Programs
Java Applets- Using SwingWorker Dave Price and Chris Loftus Computer Science Department University of Wales, Aberystwyth.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Övning 5. Repetition klasser class Rektangel { private static int antal = 0; private double längd; private double bredd; public Rektangel(double l, double.
Computer Science 209 Applets. Applications and Applets A Java application runs on a stand-alone computer and may connect to other computers via sockets.
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
More design patterns The ADAPTER Pattern Actions and the COMMAND Pattern Actions and the COMMAND Pattern The FACTORY METHOD Pattern The PROXY Pattern The.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
AP Computer Science.  Not necessary but good programming practice in Java  When you override a super class method notation.
Chapter 8 Objects & Classes. Definition of Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) uses the analogy of real objects as a template.
CSS446 Spring 2014 Nan Wang.  To learn how to choose appropriate classes for a given problem  To understand the concept of cohesion  To minimize dependencies.
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[]
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
In the name of Allah The Proxy Pattern Elham moazzen.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Using Java Class Library
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
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.
Introduction to Applets Chapter 21. Applets An applet is a Java application that is intended to be invoked and executed through a Web browser. Click Here.
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
1 Enums (Chapter 4) To enumerate is: to name things one after another in a list Java has a type, called an enum, where a programmer specifies a finite.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
Introduction to programming in java Lecture 16 Random.
GUIs Model/View/Controller Layouts
Software Development Java Classes and Methods
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Computer Science 209 The Singleton Pattern.
Singleton design pattern
More About Objects and Methods
CS 350 – Software Design Singleton – Chapter 21
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Take out a piece of paper and PEN.
Take out a piece of paper and PEN.
Computer Science 209 Images and GUIs.
CSC 205 Java Programming II
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 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(); private Die die2 = 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 import javax.swing.*; public class Card implementsComparable { private String suit; private int rank; public Card(String suit, int rank){ this.suit = suit; this.rank = rank; } Card queenOfSpades = new Card("spades", 12); Card twoOfHearts = new Card("hearts", 2); Suits are strings, but should not be just any strings Must check and throw exceptions to enforce proper use

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

public class Suit implements Comparable { 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, theyre 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);