Home arrow static arrow Java Programming [Archive] - Creating a single class
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Creating a single class
This topic has 20 replies on 2 pages.    1 | 2 | Next »

Posts:98
Registered: 6/8/04
Creating a single class  
Jul 8, 2004 9:55 AM



 
Hi,

I have a class (actually 2 but the principle should apply to both) that will act like a Factory (hope I'm using the correct term!).

Now what happens is a Results class is created for every request made to my servlet and the Factory class goes and retrieves the results, returning a Results class to be sent as a response.

Currently the Factory class is just a standard class created when the servlet is initialised but having searched the net and these forums I've figured since there will only ever been one instance I should make it a final class with static methods and variables (structured in the same way as the java Math class).

Now here are the questions.

1. Is this the right way of doing this?

2. The variables of this Factory class are pretty much just configuration data to setup the connections. I'd like to store this in a properties file and load it upon servlet/Factory creation how can I go about doing this?

3. If I make the member variables static final (as they should be constants) does that mean I have to give them a value as soon as I declare them in the code or would it be possible to load the values in as in question 2.

4. I had a look at the Singleton Pattern, can I avoid using this if my Factory class will never be extended?

Thanks for any help.
 

Posts:24,036
Registered: 2/3/03
Re: Creating a single class  
Jul 8, 2004 10:03 AM (reply 1 of 20)



 
1. Is this the right way of doing this?

"Right" is too subjective a term. Your way is not "wrong". Whether it's right or not depends on the context.

2. The variables of this Factory class are pretty much
just configuration data to setup the connections. I'd
like to store this in a properties file and load it
upon servlet/Factory creation how can I go about doing
this?

Store the properties file in the classpath, and use the standard format. You can use the Properties class to load the file contents using the Class.getResourceAsStream() method.

3. If I make the member variables static final (as
they should be constants) does that mean I have to
give them a value as soon as I declare them in the
code or would it be possible to load the values in as
in question 2.

You can't make them final if you're loading them from an external source.

4. I had a look at the Singleton Pattern, can I avoid
using this if my Factory class will never be extended?

Again, it depends. If you don't mind the potential for more than one instance of your Factory class being created, you can avoid the Singleton pattern.

§
 

Posts:24,036
Registered: 2/3/03
Re: Creating a single class  
Jul 8, 2004 10:05 AM (reply 2 of 20)



 
w.r.t. #2: [url=http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html]Smartly load your properties[/url]
 

Posts:22
Registered: 3/2/00
Re: Creating a single class   
Jul 8, 2004 11:46 AM (reply 3 of 20)



 
w.r.t #3

public static final String someProperty = getProperty("someProperty"); private static String getProperty(String key) {    try {        // load the config data from wherever        return getDataFromSomewhere(key);    } catch (Exception e) {        // log failure        return null;    }} 
 

Posts:24,036
Registered: 2/3/03
Re: Creating a single class   
Jul 8, 2004 11:49 AM (reply 4 of 20)



 
w.r.t #3

Ah yes. Good call - thanks.
 

Posts:1,652
Registered: 8/4/03
Re: Creating a single class  
Jul 8, 2004 12:04 PM (reply 5 of 20)



 
[See embedded comments]

I have a class (actually 2 but the principle should
apply to both) that will act like a Factory (hope I'm
using the correct term!).

Is there more than one type of result that can be returned? If not, you're kind of going sideways to the objective of a factory.

This is the stated intent of the AbstractFactory pattern, "Provide an interface for creating families of related or dependent objects without specifying their concrete classes."

This is the stated intent of the Builder pattern, "Separate the construction of a complex object from its representation so that the same construction process can create different representations. "

It sounds to me like it more closely resembles a Builder situation than a Factory, but there's always more than one way to skin a cat.


Now what happens is a Results class is created for
every request made to my servlet and the Factory class
goes and retrieves the results, returning a Results
class to be sent as a response.

Currently the Factory class is just a standard class
created when the servlet is initialised but having
searched the net and these forums I've figured since
there will only ever been one instance I should make
it a final class with static methods and variables
(structured in the same way as the java Math class).

An AbstractFactory pattern implementation will do this and saves you from having to create any instances of the class.

Now here are the questions.

1. Is this the right way of doing this?

It's one right way to do it. There are others, among them a Singleton, an AbstractFactory, a Builder (and the list goes on).


2. The variables of this Factory class are pretty much
just configuration data to setup the connections. I'd
like to store this in a properties file and load it
upon servlet/Factory creation how can I go about doing
this?

I agree with putting these values into a properties file for a couple of reasons. First because that information is implementation data not application design data. Second because it allows you to change them without having to redeploy the application.


3. If I make the member variables static final (as
they should be constants) does that mean I have to
give them a value as soon as I declare them in the
code or would it be possible to load the values in as
in question 2.

You cant have this both ways. They can either be loaded from an external source (recommended) or they can be constants in which case you would want to store them in a class file of their own. An upside to making them constants is that they're easier to get to if you need them, and such. Downside, if you ever need to change one of the values for any reason you now have to redepoy the application.

4. I had a look at the Singleton Pattern, can I avoid
using this if my Factory class will never be extended?

Either a Singleton or a Factory can be extended whether they should be or not, now that's a different discussion entirely.

Still another twist would be if you wanted to use a basic methodology (say AbstractFactories) for lots of things in your app. You could create a JoesSuperAbstractFactorySuperClass and extend it to make the multitude of factories you wanted. Or you could create the SuperAbstractFactoryInterface and implement it in each of your factories. Which one's right? Both, just depends on what you want out of it. If there's common behavior you want all of them to have, it might be best to go with the super class approach. If there's no common behavior, but you want to impose a common model, it might make more sense to go with the interface.


Thanks for any help.

You're welcome. I hope my rambling waffle has been of some help, or at least entertainment value.
 

Posts:27,518
Registered: 11/3/97
Re: Creating a single class  
Jul 8, 2004 12:05 PM (reply 6 of 20)



 

3. If I make the member variables static final (as
they should be constants) does that mean I have to
give them a value as soon as I declare them in the
code or would it be possible to load the values in as
in question 2.

You can't make them final if you're loading them from
an external source.

I don't think that is correct.

Static finals can be initialized in a static initializer. And of course that can do any complicated thing that one wants.

(Not that this is necessarily a good way to do it.)
 

Posts:24,036
Registered: 2/3/03
Re: Creating a single class  
Jul 8, 2004 12:07 PM (reply 7 of 20)



 
You can't make them final if you're loading them
from
an external source.

I don't think that is correct.

Ack.
 

Posts:98
Registered: 6/8/04
Re: Creating a single class  
Jul 9, 2004 5:21 AM (reply 8 of 20)



 
Wow, thanks everyone.

Ok, I took a better look at the Factory pattern and realised what I was doing wasn't quite the same!

If for example I had this:

House - which has many difference objects types inside. i.e. people, furniture

How would house be used in a Factory pattern to get the contents because at the moment I'm doing something like this.

myPerson = HouseFactory.getPerson("bob");
myFurniture = HouseFactory.getFurniture("sofa");

Also with regards to loading in the properties using the methods descibed in the above posts; If the data within the properties file were to change would this be updated within the servlet or would it need to be reloaded?

Thanks.
 

Posts:98
Registered: 6/8/04
Re: Creating a single class  
Jul 9, 2004 7:48 AM (reply 9 of 20)



 
Forgot to add...

Because I'm using a final class with a private constructor and static methods I figured the constructor would never get called because an instance of the class doesn't get created. Anyway after testing it looks like my suspicions were right.

So here's another problem. Before I changed this class from a 'normal' one to what it is now I was using the consructor to initialise the (configuration) member variables. Now I'm going to go the way of using properties but obviously that won't solve the constructor issue.

One solution would be to initialise them as they are declared but how can I get around something with a try / catch block that needs to check an object variable was successfully created?
 

Posts:27,518
Registered: 11/3/97
Re: Creating a single class  
Jul 9, 2004 8:34 AM (reply 10 of 20)



 
Wow, thanks everyone.

Ok, I took a better look at the Factory pattern and
realised what I was doing wasn't quite the same!

If for example I had this:

House - which has many difference objects types
inside. i.e. people, furniture

How would house be used in a Factory pattern to get
the contents because at the moment I'm doing something
like this.

myPerson = HouseFactory.getPerson("bob");
myFurniture = HouseFactory.getFurniture("sofa");

As I understand your description you are talking about a singleton, not a factory.

Also with regards to loading in the properties using
the methods descibed in the above posts; If the data
within the properties file were to change would this
be updated within the servlet or would it need to be
reloaded?

If the JVM is running and the property file changes then something needs to do the update. If you are using final then that will not be possible.
 

Posts:31,095
Registered: 4/30/99
Re: Creating a single class  
Jul 9, 2004 8:34 AM (reply 11 of 20)



 
If for example I had this:

House - which has many difference objects types
inside. i.e. people, furniture

How would house be used in a Factory pattern to get
the contents because at the moment I'm doing something
like this.

myPerson = HouseFactory.getPerson("bob");
myFurniture = HouseFactory.getFurniture("sofa");

This is just a description of composition, in which one Java object contains references to other Java objects. There are no factories required. Code might look like this:
House h1 = new House("4444 West Fourth");Person bob = h1.getPerson("bob");Furniture inyourdreams = h1.getFurniture("wide-screen HDTV");
PC²
 

Posts:27,518
Registered: 11/3/97
Re: Creating a single class  
Jul 9, 2004 8:39 AM (reply 12 of 20)



 

Because I'm using a final class with a private
constructor and static methods I figured the
constructor would never get called because an instance
of the class doesn't get created. Anyway after testing
it looks like my suspicions were right.

So here's another problem. Before I changed this class
from a 'normal' one to what it is now I was using the
consructor to initialise the (configuration) member
variables. Now I'm going to go the way of using
properties but obviously that won't solve the
constructor issue.

One solution would be to initialise them as they are
declared but how can I get around something with a
try / catch block that needs to check an object
variable was successfully created?

Several confusing things there.

First there is nothing wrong with leaving the initialization in the constructor. Your static methods use a single instance of the constructed class. This is a common usage for singletons.

Secondly dealing with exceptions requires you to decide what impact would a failure to load have on your application.

There are three possible ways you can handle it.
- Have default values for all of the properties. If the property file fails then the default values get use. You would do this if the properties are not all that important.
- Through a runtime exception if the property file load fails. You use a runtime exception so you do not explicitly need to catch it - similar to an out of memory error in java. You do this because the property file must be loaded for the app to succeed.
- Via an initialization routine that throws a checked exception. In this case you are deferring how serious the problem is to someone else (but they must call the initialization routine.)
 

Posts:98
Registered: 6/8/04
Re: Creating a single class  
Jul 9, 2004 2:47 PM (reply 13 of 20)



 
I'm not using the Singleton pattern so I don't believe the constructor is ever being called. The class is defined as public final class and ALL the members and methods are static.

One of the members is a URL which needs creating within an try / catch block i.e.

// constructor
private MyStaticClass()
{
try {
MyStaticClass.aWebsite = new URL("http://www.website.com");
}
catch (MalformedURLException e) {
System.err.println(e.toString());
}
....
}

The problem is I can't have this within the class member declaration because of the exception handling and I can't have it in the constructor because it's never called (I think?). So I'm a bit stuck on where to put it?
 

Posts:6,750
Registered: 1/25/04
Re: Creating a single class  
Jul 9, 2004 3:12 PM (reply 14 of 20)



 
Put it in a static initializer.
private static URL aWebsite; static { try { MyStaticClass.aWebsite = new URL("http://www.website.com"); } catch (MalformedURLException e) { e.printStackTrace(); // orthrow new RuntimeException(e);// or whatever }}
 
This topic has 20 replies on 2 pages.    1 | 2 | Next »