3

I saw somewhere on SO today a design pattern that was used to illustrate a point about immutable objects in Java. The idea is to allow the user to set the value for whatever properties he wants during construction, and it looks something like this:

MyObject obj = new MyObject().name("Foo")
                             .height(5)
                             .width(3)
                             .color("blue")
                             .age(7);

Is there a name for this pattern?

In C++ I know you can just return a pointer to this in each function. How is it done the same way in Java?

For immutable objects, do you have to make a new copy of the object for each property you want to set?

Cory Klein
  • 51,188
  • 43
  • 183
  • 243
  • 1
    Check out this Q/A:http://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern - specifically the most upvoted one – JRaymond Sep 20 '12 at 22:24

4 Answers4

3

If you want to construct an immutable object with approximately this style, you likely want the Builder pattern.

The chaining visible in this is also known as a Fluent interface and is indeed enabled by returning this.

With your code using the fluent interface on the actual object under construction, the object won't be immutable if all the methods setting things are in fact mutators. If these methods all return a new object instead of this it could be immutable.

Don Roby
  • 40,677
  • 6
  • 91
  • 113
1

This is NOT the Builder pattern as mentioned in the comments by others.

It is the http://en.wikipedia.org/wiki/Fluent_interface, which is similar but not the same.

Your last two questions I think are somewhat correlated, as you can implement this pattern both in a mutable and immutable way.

If you implement it mutable, then for each method you alter the state and return this:

public class UsefulThing {

   Integer state;

   public UsefulThing(Integer state) {
      this.state=state;
   }

   public UsefulThing alter(Integer newState) {
     state = newState;
     return this;
   }
}

For an immutable implementation, you create a new object based on the one supplied and return that.

public class UsefulThing {

   Integer state;

   public UsefulThing(Integer state) {
      this.state=state;
   }

   public UsefulThing alter(Integer newState) {

     return new UsefulThing(newState);
   }
}
Istvan Devai
  • 3,962
  • 23
  • 21
1

This looks like a form of the builder pattern (though really, it's not).

Usually (using your example and assuming it's immutable) it follows a pattern similar to this:

public class MyObject {
    private final String name;
    private final int height;
    private final int width;
    private final String color;
    private final int age;

    private MyObject(Builder builder) { // Notice this is private
        name = builder.name;
        height = builder.height;
        width = builder.width;
        color = builder.color;
        age = builder.age;
    }

    // Getters

    public static class Builder {
        // Initialize these to defaults if you have any
        private String name;
        private int height;
        private int width;
        private String color;
        private int age;

        // Getters as usual

        // Every setter looks like this:
        public Builder setName(String name) {
            this.name = name;
            return this;
        }

        // Other setters

        public MyObject build() {
            return new MyObject(this);
        }
    }
}

Then to use it:

MyObject obj = new MyObject.Builder()
        .setName("Foo")
        .setHeight(5)
        .setWidth(3)
        .setColor("blue")
        .setAge(7)
        .build();

You can also reuse the builder:

MyObject.Builder builder = new MyObject.Builder();
MyObject obj1 = builder
        .setName("Foo")
        .setHeight(5)
        .setWidth(3)
        .setColor("blue")
        .setAge(7)
        .build();
MyObject obj2 = builder
        .setName("Bar")
        .build();

Here, obj2 will have the same properties as obj1 for all but name.

This is usually an alternative to long constructors. It can also be used for an object where all the information isn't available immediately and you don't want to declare a bunch of variables yourself everywhere you need to create your object. From the last example, you see it can be used if you have lots of objects you want to initialize with the same properties without having to pass those properties over and over again.

The result is that you have an immutable object, but you don't have to set/pass all of the variables at the same time like you would with a constructor or a static factory method.

Here are some references:

  • Wikipedia builder pattern page
  • OODesign.com's builder pattern page (also details how you can use interfaces for the builder pattern)
  • Joshua Bloch's Effective Java - 2nd Edition is an excellent source of information about some of the patterns (and anti-patterns) in Java.
Brian
  • 17,079
  • 6
  • 43
  • 66
0

This is an example of the Builder Pattern.

A more typical usage would be:

MyObject obj = new MyObjectBuilder().name("Foo").blah().build();

Note the use of a distinct builder class.

dty
  • 18,795
  • 6
  • 56
  • 82