Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.sibomots;
- // $0.02
- // Cannonical Builder pattern usage:
- // BuildableThing myThing = new BuildableThing().setColor("red").setMass(10).setDensity(2.4f);
- // Pedantic
- // BuildableThing myOtherThing = new BuildableThing.setColor("crap").setMass(100).setDensity(1.0f).build();
- // The need to book-end the call with a .build() is not necessary in a Builder pattern. It signifies a bit
- // of the implementation to finally construct a new BuildableThing isn't really over until build() puts a bow on
- // the object instance.
- // I prefer the Cannonical approach.
- // A lot of the time, Builder pattern is used for when a Class has a tremendous number of
- // parameters that would make constructors really unweildlly.
- public class BuildableThing {
- // If the number of fields needed on the Constructor is more than 4, likely the best way to go
- // is to make it use a Builder pattern.
- // Eg:
- // BuildableThing myBestThing = new BuildableThing(); // OK, no builder needed.
- // BuildableThing myBestThing2 = new BuildableThing("green"); // no builder needed.
- // BuildableThing myBestThing3 = new BuildableThing("orange", 10); // no builder needed.
- // BuildableThing myBestThing4 = new BuildableThing("orange", 10, 5.4f); // no builder needed, getting close
- // BuildableThing myBestThing5 = new BuildableThing("orange", 10, 5.4f, 1); // builder needed, out of hand!
- //
- // Rationale:
- //
- // As the number of arguments increase, it's more difficult to keep straight which parameter goes in which
- // order and the code becomes difficult to read.
- // Plus, what if in making a BuildableThing, I want a color and a density, but not a mass. Or some other
- // combination of "attributes". In other words, a BuildableThing needs a set of values defined. How many?
- // If the answer is "we don't care" or "don't know", then Builder fits well.
- //
- // Which gets us back to the .build() method. If the required fields to "set" are indeed non trivially important
- // then build() can perform the check to see if they were set and throw/error out. That's one effect of that bookend
- // method.
- private String color;
- private int mass;
- private float density;
- private int x;
- private int y;
- private int z;
- // etc..
- public BuildableThing()
- {
- // initialize any member data, if necessary, right here.
- }
- public BuildableThing setColor(String color)
- {
- this.color = color;
- return this;
- }
- public BuildableThing setMass(int mass)
- {
- this.mass = mass;
- return this;
- }
- public BuildableThing setDensity(float density)
- {
- this.density = density;
- return this;
- }
- public BuildableThing setX(int x)
- {
- this.x = x;
- return this;
- }
- }
Add Comment
Please, Sign In to add comment