Introduction
Builder pattern is one of creational design pattern. It builds a complex object by building separated parts and finally integrates those parts and makes the complex object. But the construction logic is not visible to the user.
Example
Suppose you have to build a computer. But you also have to build computer parts such as processor, mother board, hard disk and RAM. So building all the parts finally integrate all the parts and build the final out put as computer (a desktop computer). So this is the example I'm going to illustrate with java. Look at the following code and try to understand the concept of Builder design pattern of java.
Computer.java
package com.blog.patterns.builder; /** * @author uditha */ public class Computer { private String processor; private String motherBoard; private String hardDisk; private String ram; public String getProcessor() { return processor; } public void setProcessor(String processor) { this.processor = processor; } public String getMotherBoard() { return motherBoard; } public void setMotherBoard(String motherBoard) { this.motherBoard = motherBoard; } public String getHardDisk() { return hardDisk; } public void setHardDisk(String hardDisk) { this.hardDisk = hardDisk; } public String getRam() { return ram; } public void setRam(String ram) { this.ram = ram; } }
Builder.java
package com.blog.patterns.builder; /** * @author uditha */ public interface Builder { public void buildProcessor(); public void buildMotherBoard(); public void buildHardDisk(); public void buildRam(); public Computer getComputer(); }
ComputerBuilder.java
package com.blog.patterns.builder; /** * @author uditha */ public class ComputerBuilder implements Builder { private Computer computer; public ComputerBuilder() { computer = new Computer(); } @Override public void buildProcessor() { computer.setProcessor("some processor"); } @Override public void buildMotherBoard() { computer.setMotherBoard("some motherboard"); } @Override public void buildHardDisk() { computer.setHardDisk("some hard disk"); } @Override public void buildRam() { computer.setRam("some ram"); } @Override public Computer getComputer() { return this.computer; } }
Director.java
package com.blog.patterns.builder; /** * @author uditha */ public class Director { public Computer buildComputer(Builder builder) { builder.buildProcessor(); builder.buildMotherBoard(); builder.buildHardDisk(); builder.buildRam(); return builder.getComputer(); } }
Main.java
package com.blog.patterns.builder; /** * @author uditha */ public class Main { public static void main(String[] args) { Director director = new Director(); Builder builder = new ComputerBuilder(); Computer computer = director.buildComputer(builder); System.out.println(computer.getProcessor()); System.out.println(computer.getMotherBoard()); System.out.println(computer.getHardDisk()); System.out.println(computer.getRam()); } }
No comments:
Post a Comment