| Useful Java Design Patterns |
|
|
|
| Written by Steve Leonard |
| Monday, 23 February 2009 14:00 |
Singleton and Flyweight PatternsThese 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. ImplementationIn both cases have only private constructors, with public methods for creation/retrieval SingletonHave 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. FlyweghtHave 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 = if (null == id) { id = positionMap.get(key); PositionId newid = new PositionId(name, portfolio);id = id = newid; } } } } } |
| Last Updated on Monday, 08 November 2010 21:11 |