developer.com
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
GPS Devices
PDA Phones & Cases
Compare Prices
Imprinted Gifts
Corporate Gifts
KVM over IP
Computer Hardware
Cell Phones
Calling Cards
Holiday Gift Ideas
Data Center Solutions
Promotional Pens
Rackmount LCD Monitor
Promotional Products

 


Web Devs:
Moonlight as a Game Developer and Win Cool Prizes by Accepting the RIA Run Challenge

Now, your mission--should you choose to accept: Take your shot at gaming stardom if you think you might have what it takes to build a cool RIA game and you could win an Xbox 360 or other fabulous prizes. Hurry! You only have until May 15, 2008 to enter. »

 
Article:
Leveraging Your Flash Development with Silverlight

You're not giving up Flash any time soon (and we don't blame you.) But if you could get your Flash application working in Silverlight, why wouldn't you? We show you the tools and techniques required to have your rockin' Flash application rolled for Silverlight. Learn more here. »

 
Article:
What Does it Take to Build the Best RIA?

With the proliferation of Rich Interactive Application (RIA) platform choices out there, you no longer have to take a one-size-fits-all approach to developing your next RIA application. Knowing the strengths (and weaknesses) of each platform can help you to decide the best RIA for your next application. »

 
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Project Management Guide: Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.

Working With Design Patterns: Singleton
By Jeff Langr

Go to page: 1  2  Next  

The singleton is perhaps the most maligned software design pattern out there. It's right up there with the visitor pattern, which is often denigrated by developers as too complex. Yet, the notion behind singleton is simple: ensure that only one instance of a specific type exists during application execution.

The default Java behavior, as with most languages, allows you to create as many instances of a given class as you want. Up until J2SE 5, Java allowed no direct way to impose a restriction on the number of instances. In J2SE 5 and later versions, you can use the enum construct to constrain how many objects of a given type exist. You can also provide a unique name for each of these known instances.

In languages such as C and C++, an enum ("enumeration") is simply a series of integral values, where each element in the series maps to a unique symbol. The use of enums allows you to craft more expressive code. In Java, the enum is better viewed as a class like any other, except for a few key differences. An enum can have constructors, methods, and fields, but it cannot be subclassed. An enum definition first supplies the names of the known instances; no other instances can be created by any means.

From a simplistic standpoint, you could consider the catalog in a library system a candidate for a singleton. After all, you don't want to have to know what books were added to what catalog. Listing 1 shows how you might implement the catalog singleton using the enum construct.

Listing 1: The catalog singleton, expressed as an enum.

import java.util.*;

public enum Catalog {
   soleInstance;

   private Map<String,Book> books = new HashMap<String,Book>();

   public void add(Book book) {
      books.put(book.getClassification(), book);
   }

   public Book get(String classification) {
      return books.get(classification);
   }
}

Not much to it, is there? Client code must refer to the single known object, soleInstance (see Listing 2).

Listing 2: Accessing the enum singleton.

import static org.junit.Assert.*;
import org.junit.*;

public class CatalogTest {
   @Test
   public void singleBook() {
      Book book = new Book("QA123", "Schmidt", "Bugs", "2005");
      Catalog.soleInstance.add(book);
      assertSame(book, Catalog.soleInstance.get("QA123"));
   }
}

If you attempt to directly instantiate another Catalog object:

   new Catalog();    // this won't compile!

...your code will not even compile, as the comment states.

Is this really a design pattern? Well, yes, it's an implementation of a design pattern, one that the Java language makes very simple.

Most developers are probably more familiar with the concept of "rolling their own" singleton. In Java, this means supplying a static-side creation method and making the constructor private. See Listing 3.

Listing 3: Hand-grown catalog singleton.

import java.util.*;

public class Catalog {
   private static final Catalog soleInstance = new Catalog();
   private Map<String,Book> books = new HashMap<String,Book>();

   public static Catalog soleInstance() {
      return soleInstance;
   }

   private Catalog() {
      // enforce singularity
   }

   public void add(Book book) {
      books.put(book.getClassification(), book);
   }

   public Book get(String classification) {
      return books.get(classification);
   }
}

The private constructor ensures that no other clients can create a Catalog object. From the client standpoint, things don't look very different (see Listing 4).

Listing 4: Accessing the hand-grown singleton.

import static org.junit.Assert.*;
import org.junit.*;

public class CatalogTest {
   @Test
   public void singleBook() {
      Book book = new Book("QA123", "Schmidt", "Bugs", "2005");
      Catalog.soleInstance().add(book);
      assertSame(book, Catalog.soleInstance().get("QA123"));
   }
}

Seems like a simple, harmless pattern. So what's all the fuss?

Go to page: 1  2  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Architecture & Design Archives

Work With InterSystems. Not Separate Systems. Rapidly develop and deploy connectable applications.
Learn about expanding business opportunities for the reseller channel. Visit IT Channel Planet.
Five Trends for Application Development & Program Management. Download Complimentary Report Now.
Guide to Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.
Whitepaper: Embeddable Content Platform for OEM's



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES