Posted By

narkisr on 01/14/09


Tagged

java pattern builder immutable


Versions (?)

An immutable Java class builder


 / Published in: Java
 

An immutable (a new object is created for each change) Java class builder pattern example.

  1. public class RadioBuilder {
  2. private int buttons;
  3. private CDPlayer cdPlayer;
  4. private MP3Player mp3Player;
  5.  
  6. public static RadioBuilder create() {
  7. return new RadioBuilder(4,
  8. CDPlayerBuilder.create().build(),
  9. MP3PlayerBuilder.create().build());
  10. }
  11.  
  12. public RadioBuilder(int buttons, CDPlayer cdPlayer, MP3Player mp3Player) {
  13. this.buttons = buttons;
  14. this.cdPlayer = cdPlayer;
  15. this.mp3Player = mp3Player;
  16. }
  17.  
  18. public RadioBuilder withButtons(int buttons) {
  19. return new RadioBuilder(buttons, cdPlayer, mp3Player);
  20. }
  21.  
  22. public RadioBuilder with(CDPlayer cdPlayer) {
  23. return new RadioBuilder(buttons, cdPlayer, mp3Player);
  24. }
  25.  
  26. public RadioBuilder with(MP3Player mp3Player) {
  27. return new RadioBuilder(buttons, cdPlayer, mp3Player);
  28. }
  29.  
  30. public Radio build() {
  31. return new Radio(buttons, cdPlayer, mp3Player);
  32. }
  33. }

Report this snippet  

You need to login to post a comment.