January 29, 2010 Design Patterns, Java
January 29, 2010 Design Patterns, Java
Imagine that you have shop where your Customers could buy Laptops with configuration they prefer. You need to develop system which will allow you easily build any configuration of Laptop for any User.
How could you easily accomplish this?
Builder is Creational Design Patter which allows you build some whole Product (Laptop) by constructing together some parts like Processor, Memory, Monitor, HDD, Battery and so on.
So your employee talks to Customer and asks questions which memory do you want and so on. Or otherwise if Customer is not technic, employee could ask “Do you need this laptop for gaming?”.
So you need some steps to construct you computer and they are defined in Abstract Builder.
public Laptop getMyLaptop(){
return laptop;
}
//mentioned steps to build laptop
public abstract void setMonitorResolution();
public abstract void setProcessor();
public abstract void setMemory();
public abstract void setHDD();
public abstract void setBattery();
}
If your Customer answers like “Yes, I wanna play… play…!!!“. You already have implementation of Concrete Builder for gaming laptop like:
Or if you Customer is business guy and he watches presentations and exel reports in plain:
To manage steps to build your Laptop basing on the answer you need Director:
Here we have usage code.
BuyLaptop shopForYou = new BuyLaptop();//director
shopForYou.setLaptopBuilder(gamingBuilder);//Customer answered that he wants to play
shopForYou.constructLaptop();
Laptop laptop = shopForYou.getLaptop();//just get what he wants
laptop.print();
Output:
Easy, simple and great pattern.
What have I learned regarding of Java?
Nothing special, just how to format strings:
code
more code
~~~~