leonarduk.com

Breadcrumbs

Home Knowledge bank Technical Skills Java Useful Java Design Patterns
Useful Java Design Patterns PDF Print E-mail
Written by Steve Leonard   
Monday, 23 February 2009 14:00

Singleton and Flyweight Patterns

These patterns are related. Singleton ensure only once instance of a class exists;  Flyweight ensures that only one each of a certain key exists.  The aim with each is to reduce resources needed.

Implementation

In both cases have only private constructors, with public methods for creation/retrieval

Singleton

Have a static member variable of the class, and have access to it via a geInstance() method.  This will check if the instance is null, if so creates it.  Then returns the instance.

Flyweght

Have a static map, e.g. WeakHashMap or ConcurrentHashMap and check if an instance for your key exists, if so return it, otherwise, create it, put in map and then return it.

private static ConcurrentMap positionMap = new ConcurrentHashMap();

public static PositionId get(String name, PortfolioId portfolio) {

String key = name + "|" + portfolio;PositionId id =

positionMap.get(key);

if (null == id) {

synchronized (key) {

id = positionMap.get(key);

if (null == id) {

PositionId newid = new PositionId(name, portfolio);id =

positionMap.putIfAbsent(key, newid);if (null == id) {

id = newid;

}

}

}

}

return id;

}

Last Updated on Monday, 08 November 2010 21:11