DOC PREVIEW
CU-Boulder CSCI 5448 - Singleton, Command, & Adaptor

This preview shows page 1-2-3-19-20-38-39-40 out of 40 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 40 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 40 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 40 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 40 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 40 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 40 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 40 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 40 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 40 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Singleton, Command, & AdaptorKenneth M. AndersonUniversity of Colorado, BoulderCSCI 4448/5448 — Lecture 22 — 11/05/2009© University of Colorado, 20091Lecture Goals• Cover Material from Chapters 5 — 7 of the Design Patterns Textbook• Singleton Pattern• Command Pattern• Adaptor Pattern• Facade Pattern2Singleton Pattern: Definition• The Singleton Pattern ensures a class has only one instance (or a constrained set of instances), and provides a global point of access to it• Useful for objects that represent real-world resources, such as printers, in which you want to instantiate one and only one object to represent each resource• Also useful for “management” code, such as a thread/connection pool• At first, Singleton may seem difficult to achieve… typically, once you define a class, you can create as many instances as you want• Foo f = new Foo(); Foo f1 = new Foo(); Foo f2 = new Foo()…• The key (in most languages) is to limit access to the class’s constructor, such that only code in the class can invoke a call to the constructor (or initializer or <insert code that creates instances here>)• Indeed, as you will see, different languages achieve the Singleton pattern in different ways3Singleton Pattern: Structurestatic getInstance() : Singletonprivate Singleton()static my_instance : SingletonSingletonSingleton involves only a single class (not typically called Singleton). That class is a full-fledged class with other attributes and methods (not shown)The class has a static variable that points at a single instance of the class.The class has a private constructor (to prevent other code from instantiating the class) and a static method that provides access to the single instance4World’s Smallest Java-based Singleton Classpublic class Singleton {12 private static Singleton uniqueInstance;34 private Singleton() {}56 public static Singleton getInstance() {7 if (uniqueInstance == null) {8 uniqueInstance = new Singleton();9 }10 return uniqueInstance;11 }12}1314Meets Requirements: static var, static method, private constructorExample source has this class in ken/smallest augmented with test code5World’s Smallest Python-Based Singleton Classclass Singleton(object):12 _instance = None34 def __new__(cls, *args, **kwargs):5 if not cls._instance:6 cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)7 return cls._instance89if __name__ == '__main__':10 a = Singleton()11 b = Singleton()1213 print "a = %s" % (a)14 print "b = %s" % (b)1516Different Approach: static var, override constructoronly 8 lines of code!Example source has this class in ken/smallest6World’s Smallest Ruby-based Singleton Classrequire 'singleton'12class Example3 include Singleton4end56a = Example.instance7b = Example.instance89puts "a = #{a}" 10puts "b = #{b}" 1112c = Example.new1314Yet a different approach, using a mechanism in Ruby called a “mixin”The “include Singleton” statement causes the Example class to be modified such that its new() method becomes private and an instance() method is added to retrieve an instance. As a bonus, it will also handle hiding allocate(), overriding the clone() and dup() methods, and is thread safe!Only 5 lines of code!7Thread Safe?• The Java and Python code just shown is not thread safe• This means that it is possible for two threads to attempt to create the singleton for the first time simultaneously• If both threads check to see if the static variable is empty at the same time, they will both proceed to creating an instance and you will end up with two instances of the singleton object (not good!)• Example Next Slide8Program to Test Thread Safetypublic class Creator implements Runnable {12 private int id;34 public Creator(int id) {5 this.id = id;6 }78 public void run() {9 try {10 Thread.sleep(200L);11 } catch (Exception e) {12 }13 Singleton s = Singleton.getInstance();14 System.out.println("s" + id + " = " + s);15 }1617 public static void main(String[] args) {18 Thread[] creators = new Thread[10];19 for (int i = 0; i < 10; i++) {20 creators[i] = new Thread(new Creator(i));21 }22 for (int i = 0; i < 10; i++) {23 creators[i].start();24 }25 }2627}2829Creates a “runnable” object that can be assigned to a thread.When its run, its sleeps for a short time, gets an instance of the Singleton, and prints out its object id.The main routine, creates ten runnable objects, assigns them to ten threads and starts each of the threads9Output for Non Thread-Safe Singleton Code• s9 = Singleton@45d068• s8 = Singleton@45d068• s3 = Singleton@45d068• s6 = Singleton@45d068• s1 = Singleton@45d068• s0 = Singleton@ab50cd• s5 = Singleton@45d068• s4 = Singleton@45d068• s7 = Singleton@45d068• s2 = Singleton@45d068Whoops!Thread 0 created an instance of the Singleton class at memory location ab50cd at the same time that another thread (we don’t know which one) created an additional instance of Singleton at memory location 45d068!10How to Fix?public class Singleton {12 private static Singleton uniqueInstance;34 private Singleton() {}56 public static synchronized Singleton getInstance() {7 if (uniqueInstance == null) {8 uniqueInstance = new Singleton();9 }10 return uniqueInstance;11 }1213}1415In Java, the easiest fix is to add the synchronized keyword to the getInstance() method. The book talks about other methods that address performance-related issues. My advice: use this approach first!11Command Pattern: Definition• The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations• Think of a Restaurant• You, the Customer, give your Waitress an Order• The Waitress takes the Order to the kitchen and says “Order Up”• The Cook takes the Order and prepares your meal• Think of the order as making calls on the Cook like “makeBurger()”• A request (Order) is given to one object (Waitress) but invoked on another (Cook)• This decouples the object making the request (Customer) from the object that responds to the request (Cook); This is good if there are potentially many objects that can respond to requests12Command Pattern:


View Full Document

CU-Boulder CSCI 5448 - Singleton, Command, & Adaptor

Documents in this Course
Django

Django

42 pages

ENRS

ENRS

30 pages

PhoneGap

PhoneGap

22 pages

Load more
Download Singleton, Command, & Adaptor
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Singleton, Command, & Adaptor and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Singleton, Command, & Adaptor 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?