473,395 Members | 1,972 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Singleton factory?

13,262 8TB
Ok i've overdone something here.

I thought I'd make a factory of singletons during lunch

Expand|Select|Wrap|Line Numbers
  1.  
  2. package factory;
  3. import java.util.*;
  4. class SingletonFactory {
  5.  static Hashtable<Class, Boolean> classes = new Hashtable<Class, Boolean>();
  6.  public static boolean forMe = false;
  7.  private SingletonFactory() {
  8.  } 
  9.  public static SingletonFactory getSingletonFactory() {
  10.   SingletonFactory me = null;
  11.   if(!forMe) {
  12.    me = new SingletonFactory();
  13.    forMe = true;
  14.   }
  15.   return me;
  16.  }
  17.  public static Object getSingleton(Object object) {
  18.   Set keys = classes.keySet();
  19.   Iterator iterator = keys.iterator();
  20.   Object single = null;
  21.   try {
  22.    while( iterator.hasNext() ) {
  23.     Class key = (Class)iterator.next();
  24.     if( key == object.getClass() ) {
  25.      if( !classes.get(key) ) {
  26.       single = key.newInstance();
  27.       classes.put(key, true);
  28.       return single;
  29.      }
  30.      else {
  31.       return null;
  32.      }
  33.     }
  34.    }
  35.   }
  36.   catch(InstantiationException iE) {
  37.    iE.printStackTrace();
  38.   }
  39.   catch(Exception e) {
  40.    e.printStackTrace();
  41.   }
  42.   return single;
  43.  }
  44.  public void addSingleton(Object object) {
  45.   if(!classes.containsKey(object.getClass())) {
  46.    classes.put(object.getClass(), false);
  47.   }
  48.  }
  49.  
  50.  public void finalize() {
  51.   Set keys = classes.keySet();
  52.   Iterator iterator = keys.iterator();
  53.   while( iterator.hasNext() ) {
  54.    Class key = (Class)iterator.next();
  55.    classes.put(key, false);
  56.   }
  57.  }
  58.  public static void main( String ... args ) {
  59.   try {
  60.    SingletonFactory factory = SingletonFactory.getSingletonFactory();
  61.    System.out.println(a.getInstance(factory));
  62.    System.out.println(a.getInstance(factory));
  63.   }
  64.   catch(Exception e) {
  65.    e.printStackTrace();
  66.   }
  67.  }
  68. }
  69.  
  70.  
And then have my singletons in the form


Expand|Select|Wrap|Line Numbers
  1.  class a {
  2.  a()  { 
  3.  }
  4.  public static a getInstance (SingletonFactory factory) {
  5.   factory.addSingleton(new a());
  6.   return (a)factory.getSingleton(new a());
  7.  }
  8. }
  9.  
This obviously works only if instances are created using the Singleton.getInstance method or through the factory.getSingleton method. I'm almost convinced that there's a way of stopping creation through
Expand|Select|Wrap|Line Numbers
  1. new Singleton() 
as well but I'm beginning to doubt that ...
Can it be done or would this factory work only if everyone creates Singletons using getInstance?
Jun 6 '07 #1
2 3887
JosAH
11,448 Expert 8TB
Your SIngletonFactory is severely broken in the method that tries to instantiate
such a factory in a lazy manner. It should look something like this:

Expand|Select|Wrap|Line Numbers
  1. private static SingletonFactory instance= null; // no instance yet
  2. public static synchronized SingletonFactory getFactory() {
  3.    if (instance == null)
  4.       instance= new SingletonFactory();
  5.    return instance;
  6. }
There's no need for a boolean to keep track of things but more important is that
the instance should be a static variable (and private preferably) and the creator
method should be synchronized just in case two threads want to create that
factory at more or less the same time.

I normally keep singletons in two maps: Map<String, String> mapping a symbolic
name to a fully qualified class name and a Map<String, Object> mapping the
symbolic name to the singleton object. If the object can't be found in the second
map, the first map is consulted and a simple:

Expand|Select|Wrap|Line Numbers
  1. String clazz= firstMap(symbolicName);
  2. Object singleton= Class.forName(clazz).newInstance();
  3. scondMap.put(symbolicName, singleton);
  4. return singleton;
  5.  
... creates the singleton if it hasn't been done so before.

kind regards,

Jos
Jun 7 '07 #2
r035198x
13,262 8TB
Your SIngletonFactory is severely broken in the method that tries to instantiate
such a factory in a lazy manner. It should look something like this:

Expand|Select|Wrap|Line Numbers
  1. private static SingletonFactory instance= null; // no instance yet
  2. public static synchronized SingletonFactory getFactory() {
  3. if (instance == null)
  4. instance= new SingletonFactory();
  5. return instance;
  6. }
There's no need for a boolean to keep track of things but more important is that
the instance should be a static variable (and private preferably) and the creator
method should be synchronized just in case two threads want to create that
factory at more or less the same time.

I normally keep singletons in two maps: Map<String, String> mapping a symbolic
name to a fully qualified class name and a Map<String, Object> mapping the
symbolic name to the singleton object. If the object can't be found in the second
map, the first map is consulted and a simple:

Expand|Select|Wrap|Line Numbers
  1. String clazz= firstMap(symbolicName);
  2. Object singleton= Class.forName(clazz).newInstance();
  3. scondMap.put(symbolicName, singleton);
  4. return singleton;
  5.  
... creates the singleton if it hasn't been done so before.

kind regards,

Jos
I was beginning to think about using two hashmaps too. Thanks I'll look into it and see what I can improve.
Jun 7 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

14
by: lawrence | last post by:
To call I would do something like: $headline = McSelectJustOneField::callDatastore("cbHeadline"); Is this the correct use of the static keyword, to implement a Singleton design?
2
by: Simon | last post by:
Hi. I don't have a problem per se, I was just wondering if anyone can offer some opinions about the best way to go about creating and disposing of a Singleton class. I have a class (handling...
4
by: Eric | last post by:
Perhaps this question has been posed before (I'd be surprised if it hasn't) but I just gotta know... Is it possible to combine the Singleton and Factory Method design patterns in the same class?...
5
by: Jake | last post by:
I'm just getting into design patterns and am not sure I fully understand the usefulness of the singleton. I know you can use it to ensure that you only have one instance of a class, but why would...
11
by: Daniel Billingsley | last post by:
Let's say I'm writing a business app and I want there to be only one instance of the Customer object for each particular customer (representing a database record) being edited. Would it be...
15
by: DBA | last post by:
Hi All, What is the diff. between a singleton class and a static class in C#?
4
by: Simon Hazelton | last post by:
Is it possible in VB.net to have a single or singleton instance of a class per specific database record. I'm writing an auction site and have a problem with resolving proxy bids, effectively I...
7
by: ThunderMusic | last post by:
Hi, I have a problem regarding singletons in C#. What I would like to do is the following ClassA is a singleton ClassB inherits from ClassA and is also a Singleton there cannot and instance of...
5
by: Markus Dehmann | last post by:
I need a Singleton for general program options so that all classes can access it. I use the code below (adapted from the Wikipedia singleton example). But the problem is if I change one variable...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.