Thursday, March 27, 2008

How to create Immutable Objects

A Strategy for Defining Immutable Objects

 

 

·  Don't provide "setter" methods — methods that modify fields or objects referred to by fields.

·  Make all fields final and private.

·  Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.

 

Eg Code here:

 
final public class ImmutableRGB {
 
    //Values must be between 0 and 255.
    final private int red;
    final private int green;
    final private int blue;
    final private String name;
 
    public ImmutableRGB(int red, int green, int blue, String name) {
        check(red, green, blue);
        this.red = red;
        this.green = green;
        this.blue = blue;
        this.name = name;
    }
    public int getRGB() {
        return ((red << 16) | (green << 8) | blue);
    }
    public String getName() {
        return name;
    }
}

 

No comments:

Post a Comment