Chapter 9 Object-Oriented Programming 523 19 // instantiate
Chapter 9 Object-Oriented Programming 523 19 // instantiate Singleton if null 20 if ( singleton == null ) 21 singleton = new Singleton(); 23 return singleton; 24 } 25 } Fig. 9.42 Class Singletonensures that only one object of its class is created (part 2 of 2). 1 // SingletonExample.java 2 // Attempt to create two Singleton objects 3 package com.deitel.jhtp4.designpatterns; 4 5 public class SingletonExample { 6 7 // run SingletonExample 8 public static void main( String args[] ) 9 { 10 Singleton firstSingleton; 11 Singleton secondSingleton; 12 13 // create Singleton objects 14 firstSingleton = Singleton.getSingletonInstance(); 15 secondSingleton = Singleton.getSingletonInstance(); 16 17 // the “two” Singletons should refer to same Singleton 18 if ( firstSingleton == secondSingleton ) 19 System.out.println( “firstSingleton and ” + 20 “secondSingleton refer to the same Singleton ” + 21 “object” ); 22 } 23 } Fig. 9.43 Class SingletonExampleattempts to create Singletonobject more than once. Fig. 9.44 Class SingletonExampleoutput shows that the Singleton object may be created only once. 9.24.2 Structural Design Patterns Structural design patterns describe common ways to organize classes and objects in a system. The gang-of-four book describes seven structural design patterns (six of which we discuss in this book): Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01