Abstract Factory pattern

Factories have been a key pattern in building applications, its fascinatingly simple, effective and to the point. When starting to learn a design oriented approach to applications or API, I would always recommend a factory pattern as one of the key starting notes of highlight in your design.

So today I am talking about the Abstract Factory pattern. Its not an “abstract” class or object that you call a pattern. But its a Factory of facotries and that is what exactly makes it so much wordingly abstract. Having “abstract” classes is there but just some other side of the coin.

When should I use an Abstract Factory:

  • Independence of how products are created, composed or represented
  • Should be configurable with one of the multiple families or products
  • You need enforcable constraints for the products used as a group
  • You need to reveal only the interfaces of products and not thier implementation as part of a bigger picture.

So lets begin with the fun.

This is how I plan to implement it:
Has A:
Product has a Specification
Factory has a Product
FactoryManager has FactoryConstants
FactoryManager has ComputerFactory

Is A:
BFactory is a ComputerFactory
AFactory is a ComputerFactory

Not shown.
ProductA is a Product
ProductB is a Product

Diagram:

AbstractFactory
AbstractFactory

Creating a simple factory that returns products.

  1. public abstract class ComputerFactory {
  2.  
  3.  public abstract String getName();
  4.  
  5.  public abstract Product[] getProducts();
  6.  
  7.  public abstract Product getProduct(int ProductID);
  8.  
  9. }

Implementation of the ComputerFactory

  1. public class AFactory extends ComputerFactory {
  2.  
  3. public String getName(){
  4. return "A";
  5. }
  6.  
  7. public Product[] getProducts(){
  8. return null;
  9. }
  10.  
  11. public Product getProduct(int productID){
  12. switch(productID){
  13. case 1:
  14. return new ProductA();
  15.  
  16. case 2:
  17. return new ProductB();
  18.  
  19. default:
  20. throw new IllegalArgumentException("Sorry you hit the wrong factory, we closed down in 1600 BC");
  21. }
  22. }
  23. }

A register base for factories. Refer to the main method for use later in this post.

  1. public interface FactoryConstants {
  2.  
  3.  public int A = 1;
  4.  public int B = 2;
  5.  
  6. }

The main Entrant class. the Factory Manager that will give the ComputerFactory resultant. Its assumed to be a Singleton as it registers as a Creator in the system (assumption).

  1. public class FactoryManager{
  2.  
  3.  private static FactoryManager factoryManager = null;
  4.  
  5.  private FactoryManager(){
  6.  
  7.  }
  8.  
  9.  public static FactoryManager getInstance(){
  10.   if(factoryManager != null){
  11.    return factoryManager;
  12.   }
  13.   else return factoryManager = new FactoryManager();
  14.  }
  15.  
  16.  public ComputerFactory getFactory(int factory) throws IllegalArgumentException{
  17.  
  18.   switch(factory){
  19.    case FactoryConstants.A:
  20.    return new IBMFactory();
  21.  
  22.    case FactoryConstants.B:
  23.    return new SUNFactory();
  24.  
  25.    default:
  26.    throw new IllegalArgumentException("Sorry you hit the wrong factory, we closed down in 1600 BC");
  27.   } 
  28.  }
  29. }

A main method to test the AbstractFactory

  1.  public static void main(String args[]){
  2.  
  3.   System.out.println(FactoryManager.getInstance().getFactory(FactoryConstants.A).getName());
  4.   System.out.println(FactoryManager.getInstance().getFactory(FactoryConstants.B).getName());
  5.   System.out.println(FactoryManager.getInstance().getFactory(3).getName());
  6.  
  7.  }

You can find the complete code listing here:
AbstractFactory source

Crocus – CSV Reader

Easy to use ready to go CSV File Reading utility. Read One or Multiple files into a RecordManager, quick access to the file with segmentation into Fields and Records. Merge Multiple CSV files in one. Listener to CSV Files.

Download Here

Organization:
A CSV file is broken up as follows
A CSVField has a group of characters
A CSVRecord has a group of CSVFields
A CSVFile has a group of record

How To Use:

Reading a Single CSVFile into a RecordManager

  1.  // Creating a single file interface
  2. CSVSingleFileInterface fileInterface = new CSVSingleFileInterface("/media/data/dev/workspace/crocus/testData/drupal-sample.csv",CSVConstants.COMMA);
  3. // Calling the read returns a CSVRecordManager i.e. in memory
  4. AbstractCSVRecordManager manager = fileInterface.read();

Reading multiple files into one RecordManager

  1. // Specify a FileSet
  2. AbstractCSVFileSet fileSet = new CSVFileSet();
  3.  
  4. // Add files to the set
  5. fileSet.addFile("testData/drupal-sample.csv");
  6. fileSet.addFile("testData/countries.csv");
  7.  
  8. // Add the fileSet to a Reading Interface
  9. CSVFileSetInterface fileSetInterface = new CSVFileSetInterface(fileSet);
  10.  
  11. //  Reading returns a manager same as in a Single file case.
  12. AbstractCSVRecordManager manager = fileSetInterface.read();

This functionality is not complete but a peak is available.
You can now specify a Listener to Pre, Post and On Add of a record.

Setting up a Listener.

To add you listener simply implement the RecordListener class

  1. // Get a Record Manager
  2. AbstractCSVRecordManager manager = fileInterface.getRecordManager();
  3.  
  4. // Add a listener to the Manager.
  5. manager.addRecordListener(this);
  1. // Implement an event listening method for listening to the RecordEvent.
  2. public void eventPerformed(RecordEvent recordEvent) {
  3. System.out.println(recordEvent.toString());
  4.  
  5. }

for further information refer to the docs.  http://www.shaafshah.com/crocus/

The Build System:

The build script supports the following targets

Build: init, clean, compile, jar, javadoc, tests

Including, Excluding files while creating compile, jar, tests

FILE DETAILS (Paths and description):

PRE RULES:

=========

CROCUS_DEV = the main directory i.e. examples from here onwards this will be the variable used for describing details.

You will need to set CROCUS_DEV env variable inorder to run the build process

Also you would need to set ANT_HOME for usage of ant. I have used Ant 1.6.5 for builds.

$CROCUS_DEV/src Holds the source code i.e. java files

$CROCUS_DEV/build Carries all the build related files

$CROCUS_DEV/build/build.xml Main build script

$CROCUS_DEV/build/include.xml patterns for inclusion of java files at the time of compilation

$CROCUS_DEV/build/exclude.xml patterns for exclusion of java files at the time of compilation

$CROCUS_DEV/build/tests_include.xml patterns for inclusion of test java files at the time of compilation

$CROCUS_DEV/build/tests_exclude.xml patterns for exclusion of test java files at the time of compilation

$CROCUS_DEV/build/tools tools used during build.

$CROCUS_DEV/build/jar_buildfiles you can simply specify a txt file with some wild card matches and name it as yourjar.jar for the build system to recognize that “yourjar.jar” will be the name for this jar that should have the packages in it as specified in this txt(yourjar.jar)

$CROCUS_DEV/build/bin Holds the uniz script and the bat file for developers to run the build script more or less as:

Windows:> %CROCUS_DEV%/build all

Linux:> $CROCUS_DEV/build.sh all

$CROCUS_DEV/build_results Holds all the results of the builds

$CROCUS_DEV/build_results/docs Created java docs

$CROCUS_DEV/build_results/classes Created classes

$CROCUS_DEV/build_results/tests Unit test results

$CROCUS_DEV/build_results/jars the jars created by the system

$CROCUS_DEV/jars/ Is the directory for jars related information

$CROCUS_DEV/jars/manifests Holds the manifests for the $CROCUS_DEV/build/jar_buildfiles.

Conventionally should use: Manifest.jarName

$CROCUS_DEV/jars/original3rdparty Holds any 3rd party vendor jars that might be used for putting in the classpath for the build system

$CROCUS_DEV/testData logically should hold all testData no matter how that might be. currently I have placed a few csv files (tabbed,comma,semicolon).

HowTo create a JDBC provider with wsadmin scripting – Jython

Last week I wrote a post about creating MQQueues with jacl. However today I am moving to Jython. This is the new scripting languauge supported by the wsadmin. The following write-up helps you create a JDBC provider using Jython in 6 easy steps on the wsadmin console.

Pre requirements:
Following should be known to start using this tutorial.

1. How to launch the wsadmin with Jython enabled.

Where will I find the wsadmin?
It is typically placed in the bin directory of your server.
In my case its lying in my RAD installation directory as
../Rational/SDP/6.0/runtimes/base_v6/bin

To invoke the wasadmin, just open your terminal and move to the bin dir where you can simply call it by typing wsadmin -lang jython. By doing so you would be invoking the default profile. if you want to specify the profile then use the switch -profileName YOURPROFILENAME

You can either paste the commands step by step or store the whole code listing in one file like DataSources.py. This means you can run this with wsadmin by specifying the -f switch.

After the wsadmin console is launched we can now move to creating the provider step by step.

STEP 1.
Identify classpath for the provider. This is a path to the jar files that need to be used by the provider. In our case its a jdbc dirver for oracle.

driverPath = 'C:\lib\ojdbc14.jar'

STEP 2.
Identify the node and cell that will hold this provider. Node/Cell is how websphere is organized. As the Provider will be created inside a node we need to know which node we are working with.

cellName=AdminControl.getCell()
nodeName=AdminControl.getNode()
node = AdminConfig.getid('/Cell:%s/Node:%s/' % (cellName,nodeName))

In the code above first we get the NodeName and CellName of the current connected server and then take the reference of it as node.

STEP 3.
Specify a template, In our case we have taken an ‘Oracle JDBC Driver (XA)’ template.
The following command will list the template for the provider specified and store it in a variable ‘providerTemplate’

providerTemplate=AdminConfig.listTemplates('JDBCProvider', 'Oracle JDBC Driver (XA)')

STEP 4.
The name for our provider. It could be any name you want to give your provider.

providerName = ['name', 'Oracle JDBC Driver (XA)']

Implementation class and classpath for driver.
It is important to give the implementation class for our provider. In some cases they can be different in ours we use the default one.

implClassName = ['implementationClassName', 'oracle.jdbc.xa.client.OracleXADataSource']

STEP 5.
The following code will just put all the above variables into a form expected by wsadmin as a temp variable jdbcAttrs.

classpath = ['classpath',driverPath]
jdbcAttrs = [providerName,  implClassName,classpath]

STEP 6.

Now is the time to create the provider. and the following will just do that. It passes the type of the provider, the node ref, the jdbcAttrs created in step 5 and the template to be used to create the provider.

provider  = AdminConfig.createUsingTemplate('JDBCProvider', node, jdbcAttrs, providerTemplate)
AdminConfig.save()

This is pretty much it. You should now be able to see the provider in the AdminConsole.

Complete code listing is as follows

driverPath = 'C:\lib\ojdbc14.jar'
cellName=AdminControl.getCell()
nodeName=AdminControl.getNode()
providerTemplate=AdminConfig.listTemplates('JDBCProvider', 'Oracle JDBC Driver (XA)')
node = AdminConfig.getid('/Cell:%s/Node:%s/' % (cellName,nodeName))
 
providerName = ['name', 'Oracle JDBC Driver (XA)']
implClassName = ['implementationClassName', 'oracle.jdbc.xa.client.OracleXADataSource']
classpath = ['classpath',driverPath]
jdbcAttrs = [providerName,  implClassName,classpath]
provider  = AdminConfig.createUsingTemplate('JDBCProvider', node, jdbcAttrs, providerTemplate)
AdminConfig.save()

Creating an SVN wrap for your build using Ant

Today after along break I would jump right on to one of the interesting topics in my den these days.

One of my friends was lately troubled with doing some SVN stuff like merging etc. And a lot of people will agree with me on their first experiences. 🙂 I think.

While Automated builds take a lot of our time I thought I could plug in with some automated merging and a few other tasks. Its hard to go over all of that in one post but I will try putting in some basic stuff to get us started.

I call it the SVN Wrap.

Step 1.
Create a simple script file for wrapping svn and our environment.

A simple bat script could look like the following

@echo off
svn %*

However some people might want to add some environment variables to it. And that is where the strength of the this file comes in. You can tailor the environment dynamically!
e.g.

set LC_ALL=C
set SVN_HOME=svn-win32-1.4.6
set PATH=%SVN_HOME%\bin;%PATH%;

FYI: By setting LC_ALL I am telling the system I disregard the default locale. Its just used as an example here. for more information refer to the svnbook at http://svnbook.red-bean.com/

Step 2.
Create the build.xml
It doesnt get simpler then this.

I have created a project with the name CI-Test

<project name="CI-Test" default="status" basedir=".">
	<description>
		This is a POC for SVN Wrap.
	</description>
</project>

Importantly I am setting a property local.branch so that I can tell svn where my code has been checked out locally.

And finally the target that will take a status of the branch. for more details on the status command you could go here.

In general this target will give a general overview of the files and thier state at the moment.

	<target name="status">
		<echo message="Following is the status for this tree."/>
		<echo message="output is logged here: status.out" />
	          <exec dir="${local.branch}" executable="ci-svn.bat" output="status.out">
            		<arg line="status"/>
          	</exec>
	</target>

With in the target there are a few echo commands but the key construct is the exec.
The exec is going to do the following

dir=”${local.branch}” – would meant execute the command in this directory
executable=”ci-svn.bat” – Identifies the executable
and finally the output attribute to show where the output of this activity goes.
The following line will pass the parameters to the executable
< arg line=”status” />
And in this case its sending a status command to svn.

For more details on exec goto. http://ant.apache.org/manual/

Now I would presume both these files in saved in one direcotry as

1. ci-svn.bat
2. build.xml

To run this simply goto your command console and once in the same directory execute by running
ant

It is assumed that all paths to java,ant and svn are set on your console or system.

As an output you should be able to see a status.out in the same directory from where you executed ant.

Hopefully this should get you started with doing some bit of svn commands from ant. And that just opens a lot of more possibilities in your build environment.

The complete code listing of the build file is as follows.

<project name="CI-Test" default="status" basedir=".">
	<description>
		This is a POC for SVN Wrap.
	</description>
 
	<property name="local.branch" value="C:\branches\my-branch"/>
 
	<target name="status">
		<echo message="Following is the status for this tree."/>
		<echo message="output is logged here: status.out" />
	          <exec dir="${local.branch}" executable="ci-svn.bat" output="status.out">
            		<arg line="status"/>
          	</exec>
	</target>
 
</project>

Creating the MQQueues with wsadmin scripting – JACL Part 2

Yesterday I wrote an article about creating and configuring the MQQueueConnectionFactory with the JACL on the wsadmin console. The other half of the article that was left out was to create the queues also.

The world looks pretty much the same today and my /etc/profile doesnt seemed to have been sourced again. Good we dont need a restart.

You would find some of the steps to be similar and that is because we are running on the same configs.

Step 1.
Identify the Provider for your Queue. By default this is the name for it. If you have created a new provider with a different name then specify it here.

set tmp1 "WebSphere MQ JMS Provider"

Step 2.
Now you would need to find the CELL NAME and the NODE NAME of your server
A typical location to my websphere profile’s Node configuration file is as follows
C:\Programs\IBM\Rational\SDP\6.0\runtimes\base_v6\profiles\test_wsp\config\cells\BNode05Cell\nodes\BNode05
The cell name in this location is after \cells\ i.e. BNode05Cell
And the node name is at the end after \nodes\ i.e. BNode05

set newjmsp [$AdminConfig getid /Cell:CELLNAMECell/Node:NODENAME/JMSProvider:$tmp1/]

Step 3.
You would now need to set the attributes that go into the queue.

To see all the attributes you can simply run the following command

$AdminConfig [required|attributes] MQQueue

i.e. required or attributes

The attributes that I will be setting in the following commands are
name, jndiName, baseQueueName, targetClient

set name [list name NAME]
set jndi [list jndiName jms/jndiName]
set baseQN [list baseQueueName BASEQUEUENAME]
set targetclient [list targetClient MQ]

You can see in the above example the target client is set to MQ it can be JMS based on your configuration.

Step 4.
Now set all parameters in one string so that they can be passed to the command as one.

set mqqAttrs [list $name $jndi $baseQN $targetclient]

Step 5.
Now to create the MQQueue use the following command. This will add the Queue to the node and cell mentioned earlier in step 2.

$AdminConfig create MQQueue $newjmsp $mqqAttrs

Once it is created it is not saved and only stays in the current session. So to save it run the following command. And you should be all set.

$AdminConfig save

You can alternatively also save this script in a file on your local system. And run it by passing it to the wasadmin. Follwing is a sample command.

wsadmin -profileName test_wsp -f $SCRIPT_FILENAME_LOCATION$

‘Complete code listing is as follows.

set tmp1 "WebSphere MQ JMS Provider"
 
set newjmsp [$AdminConfig getid /Cell:HOSTNAMENode04Cell/Node:HOSTNAMENode04/JMSProvider:$tmp1/]
 
set name [list name Q.REPLY]
set jndi [list jndiName jms/Q.REPLY]
set baseQN [list baseQueueName Q.SYSTEM]
set targetclient [list targetClient MQ]
set mqqAttrs [list $name $jndi $baseQN $targetclient]
 
$AdminConfig create MQQueue $newjmsp $mqqAttrs
 
$AdminConfig save

Creating the MQQueueConnectionFactory with wsadmin scripting – JACL Part 1.

While working my way in some piece of long java code I came across this huge pile of sand that just shattered me off every bit of patience I was left with. The dilemma all of us face every second day. CONFIGURATIONS!!

While my sarcastic mind was just saying Congratulations to me instead. And just how the – would you expect me to start configuring now.

So what exactly is my problem? I have a list of MQs, Factories, datasource, providers etc.. that I need to configure. And every time I create a new profile on my RAD (Rational Application Developer) I have to manually goto the Admin console and configure them.

With the very useless bit of linux I am acquainted too I cant live with clicks at least while programming.

As I am working with websphere and its a biggy in all those names I thought the guys would be smart and would at least have something in the box for *people like me. Well guess what I was right.

IBM has provided two languages for scripting.

1. JACL
2. Jython

If I am not wrong JACL will be deprecated out in future releases and Jython would be the tool for our scripting bit. [ Link here ]

In this article I will just go briefly with JACL and move to Jython in the next version where we will be able to configure the data sources in the websphere.

So what exactly is JACL. or pronounced as “JACKAL”

Jacl, Java Command Language, is much like/version of the Tcl scripting language for the Java. It runs on the JVM much like we hear about JRuby and the interpreter is written completely in Java.

For more details on the language itself you could go [ here ]

Lets get down to business: How to create a Webspehere MQ Connection Factory with wsamdin using JACL.
You would already have some of the details of the queues but some you will need to extract.

Step 1.
Identify the Provider for your Factory. By default this is the name for it. If you have created a new provider with a different name then specify it here.

set tmp1 "WebSphere MQ JMS Provider"

Step 2.
Now you would need to find the CELL NAME and the NODE NAME of your server
A typical location to my websphere profile’s Node configuration file is as follows
C:\Programs\IBM\Rational\SDP\6.0\runtimes\base_v6\profiles\test_wsp\config\cells\BNode05Cell\nodes\BNode05
The cell name in this location is after \cells\ i.e. BNode05Cell
And the node name is at the end after \nodes\ i.e. BNode05

set newjmsp [$AdminConfig getid /Cell:CELLNAMECell/Node:NODENAME/JMSProvider:$tmp1/]

Step 3.
Now you need to specify the Factories properties.

The properties I plan to setup are as follows.
Name, jndiName,QueueManager, sname, port, channel, ttype, xaenabled

To check what are the required parameters for the Factory you can run the following command on the wsadmin console.

$AdminConfig required WASQueueConnectionFactory

Example output:

wsadmin $AdminConfig required WASQueueConnectionFactory
Attribute                       Type
name                            String
jndiName                        String

Where will I find the wsadmin?
It is typically placed in the bin directory of your server.
In my case its lying in my RAD installation directory as
../Rational/SDP/6.0/runtimes/base_v6/bin

To invoke the wasadmin, just open your terminal and move to the bin dir where you can simply call it by typing wsadmin.  By doing so you would be invoking the default profile. if you want to specify the profile then use the switch -profileName YOURPROFILENAME

To see the all parameters required and optional write the following command on the console.

$AdminConfig attributes WASQueueConnectionFactory

Example output:

wsadmin $AdminConfig attributes WASQueueConnectionFactory
"XAEnabled boolean"
"authDataAlias String"
"authMechanismPreference ENUM(BASIC_PASSWORD, KERBEROS)"
"category String"
"connectionPool ConnectionPool"
"description String"
"jndiName String"
"logMissingTransactionContext boolean"
"manageCachedHandles boolean"
"mapping MappingModule"
"name String"
"node String"
"preTestConfig ConnectionTest"
"propertySet J2EEResourcePropertySet"
"provider J2EEResourceProvider@"
"providerType String"
"serverName String"
"sessionPool ConnectionPool"
"xaRecoveryAuthAlias String"

I have added some extra optional parameters for those of us who are using extra options.

set name [list name NAME]
 
set jndi [list jndiName jms/JNDINAME]
 
set qManager [list queueManager QMANAGER]
 
set sname [list host HOSTNAME]
 
set port [list port 1414]
 
set channel [list channel CHANNEL]
 
set ttype [list transportType CLIENT]
 
set xa [list XAEnabled True|false]

Step 4.
Now set all parameters in one string so that they can be passed to the command as one.

set mqcfAttrs [list $name $jndi $qManager $sname $port $channel $ttype $xa]

Step 5.
Now to create the Factory use the following command. This will add the factory to the node and cell mentioned earlier in step 2.

$AdminConfig create MQQueueConnectionFactory $newjmsp $mqcfAttrs

Once it is created it is not saved and only stays in the current session. So to save it run the following command. And you should be all set.

$AdminConfig save

You can alternatively also save this script in a file on your local system. And run it by passing it to the wasadmin. Follwing is a sample command.

wsadmin -profileName test_wsp -f $SCRIPT_FILENAME_LOCATION$

Complete code listing is as follows.

set tmp1 "WebSphere MQ JMS Provider"
 
set newjmsp [$AdminConfig getid /Cell:CELLNAMECell/Node:NODENAME/JMSProvider:$tmp1/]
 
set name [list name NAME]
 
set jndi [list jndiName jms/JNDINAME]
 
set qManager [list queueManager QMANAGER]
 
set sname [list host HOSTNAME]
 
set port [list port 1414]
 
set channel [list channel CHANNEL]
 
set ttype [list transportType CLIENT]
 
set xa [list XAEnabled false]
 
set mqcfAttrs [list $name $jndi $qManager $sname $port $channel $ttype $xa]
 
$AdminConfig create MQQueueConnectionFactory $newjmsp $mqcfAttrs
 
$AdminConfig save

More Resources:

[http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.nd.doc/info/ae/ae/rmig_deprecationlist.html]

[http://publib.boulder.ibm.com/infocenter/imshelp1/v3r0/index.jsp?topic=/com.ibm.sif.doc/jaclabout.html]

 

Quick start Singleton – Walk through

This being my first existence on the network and I just want to make sure that I would come back to this blog page again sometime and keep on writing. For now this is a quick 5 min walk through of getting your hands dirty on the Singleton Pattern. As any ones first pattern Singleton always seems to be the easiest to adapt and ironically always the mistress of your pains; when you realize the act wasn’t right in the first place.
More details on that later.

This post should help you to get your hands right on the Singleton Pattern and find the kind there off.

Like any other pattern Singleton also has an objective behind it. What is that?

Motivation:

A Singleton ensures that a class has only one instance, and provides a global point of access to that class.

Benefits
The very simple benefits of a singleton can be:

* Controlled access
* Permits a variable number of instances
* Reduced name space

When to use:
There must be exactly once instance of a class

How to use: Walk Through

1. Create a class

  1. public class SimplySingleton{}

2. Declare a member variable. This variable will be used for keeping the singleton instance.

It has to be private so that it is not accessible from anywhere else. It has to be static so that it holds only one instance in all entirety.

  1. private static SimplySingleton simplySingleton = null;

3. Declare a private constructor.

Creating a private constructor would mean no one else can instantiate this class.

  1. private SimplySingleton(){}

4. So now everything seems private how do we access it. Create a global access point.

  1. public static SimplySingleton getInstance(){}

How would I access it from outside SimplySingleton.getInstance();

This method should return a SimplySingleton instance.

So here comes the logic to create the one and only instance.

  1. // 4a. is the variable null?
  2. if(simplySingleton != null)
  3. return simplySingleton;
  4. // 4b. if not assign it an instance.
  5. else return simplySingleton = new SimplySingleton();

Following is the complete code listing for writing a Singleton.

  1. // Declaring the class
  2. public class SimplySingleton {
  3.  
  4. // 1. a private and a static member variable
  5.  
  6. private static SimplySingleton simplySingleton = null;
  7.  
  8. // 2. a private constructor
  9.  
  10. private SimplySingleton(){}
  11.  
  12. // 3. a global access point
  13.  
  14. public static SimplySingleton getInstance(){
  15. // 4a. is the variable null?
  16. if(simplySingleton != null)
  17. return simplySingleton;
  18. // 4b. if not assign it an instance.
  19. else return simplySingleton = new SimplySingleton();
  20. }
  21.  
  22. }

Following are some good resources for in depth peek into the Singleton Pattern.

More Resources:

http://en.wikipedia.org/wiki/Singleton_pattern

http://radio.weblogs.com/0122027/stories/2003/10/20/implementingTheSingletonPatternInJava.html

http://www.oodesign.com/singleton-pattern.html

http://www.oaklib.org/docs/oak/singleton.html