Safe Constants pattern question
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Cristian_Caprar
Posted On:   Tuesday, July 16, 2002 12:36 AM

Hi everybody. Here is my problem: I want to create a class with only 4 instances as public static members and use them instead of normal constants (ViewMode.TEXT, VieMode.DETAILS, etc.). So I declared those 4 instances as public static members of their class, made the constructor private and now I need to initialize the 4 instances. I can do it from a static initializer, but I need to pass a config object to the constructor. So this is not a very good solution. Another option is to have a static method for init that receives the config object and constructs the 4 instances, but how can I protect the instances being accesses before init has been called? Any design suggestions?    More>>

Hi everybody.


Here is my problem: I want to create a class with only 4 instances as public static members and use them instead of normal constants (ViewMode.TEXT, VieMode.DETAILS, etc.).


So I declared those 4 instances as public static members of their class, made the constructor private and now I need to initialize the 4 instances. I can do it from a static initializer, but I need to pass a config object to the constructor. So this is not a very good solution.


Another option is to have a static method for init that receives the config object and constructs the 4 instances, but how can I protect the instances being accesses before init has been called?


Any design suggestions?


Thanks,


Cristian

   <<Less

Re: Safe Constants pattern question

Posted By:   Christopher_Koenigsberg  
Posted On:   Tuesday, July 16, 2002 08:28 AM

If they are just "constants", then what "config object" do you need for the constructors?



Can you have the constructor just take a string arg, and then call it for each instance in the declaration? (e.g.




public class ViewMode {
private final String name;
private ViewMode(String name)
{this.name = name; }

public String toString()
{return name; }

public static final ViewMode TEXT = new ViewMode('text');
public static final ViewMode DETAILS = new ViewMode('details');

......
}


In Josh Bloch's maximally cool book "Effective Java" (ISBN 0-201-31005-8, Sun Java Series, Addison Wesley), on p. 105 under "Item 21: Replace enum constructs with classes" he does recommend what you are doing, and gives an example (he calls it the "typesafe enum pattern".

Re: Safe Constants pattern question

Posted By:   Gautam_Marwaha  
Posted On:   Tuesday, July 16, 2002 01:44 AM

Consider the following:


1. private non-static member variables

2. public accessor methods (getter methods) to return members

3. public constructor with config passed into it, sets values for the member variables using the config

4. Usage: make object passing the config, use getters to get the member variable values

About | Sitemap | Contact