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
Laptop Batteries
Shop Online
Imprinted Promotions
Dental Insurance
Computer Deals
Web Design
Best Price
Server Racks
KVM Switches
Corporate Gifts
Compare Prices
Promote Your Website
Find Software
Online Education

 


Download these IBM resources today!
e-Kit: IBM Rational Systems Development Solution
With systems teams under so much pressure to develop products faster, reduce production costs, and react to changing business needs quickly, communication and collaboration seem to get lost. Now, theres a way to improve product quality and communication.

Webcast: Asset Reuse Strategies for Success--Innovate Don't Duplicate!
Searching for, identifying, updating, using and deploying software assets can be a difficult challenge.

eKit: Rational Build Forge Express
Access valuable resources to help you increase staff productivity, compress development cycles and deliver better software, fast.

Download: IBM Data Studio v1.1
Effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life.

eKit: Rational Asset Manager
Learn how to do more with your reusable assets, learn how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse.
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: Prototype
By Jeff Langr

Go to page: 1  2  3  Next  

Imagine a library clerk adding stacks of new books and movies into a library system. The clerk uses a scanner to swipe the bar code that appears on the book. (For simplicity's sake, assume that the bar code is the same as the book's classification number.)

For the first copy of a book added to the library, the system makes an external API call to determine basic book information, such as author (or director, for movies), title, and year published. The lookup is slow. Further, the clerk must visually verify the information coming back, and sometimes must correct inaccurate information.

Listing 1 shows an implementation for the catalog based on these requirements. The test demonstrates that client code is responsible for creating book or movie objects and populating them with appropriate data. Presume that this client is where the call to the external API takes place. Once the material object exists, client code adds it to the catalog by calling addNew.

Listing 1: A simple catalog.

// CatalogTest.java
import static org.junit.Assert.*;

import java.util.*;
import org.junit.*;

public class CatalogTest {
   private Catalog catalog;

   @Before
   public void initialize() {
      catalog = new Catalog();
   }

   @Test
   public void isEmptyOnCreation() {
      assertEquals(0, catalog.size());
   }

   @Test
   public void addNewBook() {
      final Book book = new Book("QA123", "author", "title",
                                 "1999", 1);
      catalog.addNew(book);
      assertEquals(1, catalog.size());
      List<Material> materials = catalog.get("QA123");
      assertEquals(1, materials.size());
      assertSame(book, materials.get(0));
   }
}

// Catalog.java
import java.util.*;

public class Catalog {
   private MultiMap<String, Material> materials =
      new MultiMap<String, Material>();

   public int size() {
      return materials.valuesSize();
   }

   public void addNew(Material material) {
      materials.put(material.getClassification(), material);
   }

   public List<Material> get(String classification) {
      return materials.get(classification);
   }
}

Many of the added materials are duplicate copies of the same title, where every piece of information remains the same (and you'll assume that the information need not be verified for these copies). The catalog can make a duplicate of an already existing material—the prototype—thus sparing the API call.

The test in Listing 2 presents the scenario where a first book is externally created and then added to the catalog. A second book is scanned. Because the scanned classification represents one that is already in the system, the client can call addCopy with only the classification. Internally, the catalog is responsible for finding the first book and using its information to create a copy.

Listing 2.

@Test
public void addCopyViaPrototype() {
   final Book book = new Book("QA123", "title", "author",
                              "1999", 1);
   catalog.addNew(book);

   catalog.addCopy("QA123");

   assertEquals(2, catalog.size());

   List<Material> materials = catalog.get("QA123");
   assertEquals(2, materials.size());
   assertSame(book, materials.get(0));

   Material copy = materials.get(1);
   assertTrue(copy instanceof Book);
   assertEquals("QA123", copy.getClassification());
   assertEquals("author", copy.getAuthor());
   assertEquals("title", copy.getTitle());
   assertEquals("1999", copy.getYear());
   assertEquals(2, copy.getCopyNumber());
}

A simple implementation, good enough to get the tests to pass, appears in Listing 3. It's not a very good implementation. Never mind that the algorithm for obtaining the copy number is probably inadequate. The real problem is that the copy method is going to get ugly. Once the test supports movies in addition to books, the copy method will require an if statement to check the material type. The code will also start to get messy with the construction details of the various object types. Changes to how books or movies get constructed will ripple into the Catalog class.

Listing 3.

public void addCopy(String classification) {
   List<Material> copies = materials.get(classification);
   materials.put(classification, copy(copies.get(0)));
}

private Material copy(Material material) {
   Book book = new Book(material.getClassification(),
         material.getTitle(),
         material.getAuthor(),
         material.getYear(),
         material.getCopyNumber() + 1);
   return book;
}

Go to page: 1  2  3  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.
Developing Intelligent Communications? Visit the Avaya DevConnect Center on DevX.
Whitepaper: Embeddable Content Platform for OEM's
Learn about expanding business opportunities for the reseller channel. Visit IT Channel Planet.
Best Practices for Developing a Web Site. Checklists, Tips & Strategies. Download Exclusive eBook Now.



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