صفحه 1:
Design Pattern Course
Builder Pattern
By :SajjadZare
Teacher :Dr. Noorhosseint
صفحه 2:
Intent
O separate theconstruction of a complex object
fromits representation so that thesame
construction process cancreate different
representations.
صفحه 3:
Example
A reader for the RTF (Rich Text Format) document be لا
abletoconvert RTF tomany text formats,
O the reader might convert RIF documents into plain
ASCII text or into a text widget that can be edited
interactively.
O The problem is that the number of possible
conversions is open-ended. Soit should be easy toadd
anew conversion without modifying the reader.
صفحه 4:
SS ---2--
while(t =getToken())
¢
switchdestinationType
2
“ASCII:
Haw
WORD:
Neve
PDF:
Have
2
2
//showConveretedResult Representation
صفحه 5:
Solution
O configure the RTFReader class witha TextConverter
object that converts RIF to another textual
representation.
O Whenever the RTFReader recognizes an RTF token,
it issues a request to the TextConverter toconvert the
token.
TextConverter objects are responsible both for لا
performing the data conversion and for
representing thetokeninaparticular format.
صفحه 6:
ل
7
ال
مایت
cs
Solution
ا ا
0ك
7
۹
0
ی
ean
Co) مهو مس وب
ea
Peet Cone
Pak
alee sGenetPaagag)
۱
صفحه 7:
Structure
Direcor Builder
۳۳3 7
ی
رما
عمجم |
صفحه 8:
Componentsin Builder Pattern
O Builder
Abstract interface for creating objects (product).
O concrete Builder
Provideimplementation for Builder. Construct andassemble
parts to build the objects.
O Director
The Director classis responsible for managing the correct
sequence of object creation. It receives a Concrete Builder asa
parameter andexecutes the necessary operations onit.
O Product
Thefinal object that will becreatedby the Director using
Builder.
صفحه 9:
Applicability
O The algorithm for creating a complex object should be
independent of the parts that makeup the object and
how they reassembled.
O The construction process must allow different
representations for the object that sconstructed.
صفحه 10:
Advantages
€ncapsulate the way acomplex object isconstructed. لآ
O Allows objects to be constructed in a multi-step
processes.
۲۲ sfides the internal representation of the product
fromthe client.
O product implementation can be swappedin and out
because the client only sees the abstract interface.
صفحه 11:
RelatedPattern
O abstract Factory
| Builder focuses on constructing a complex object step by step
while Abstract Factory emphasizes a family of product
objects
| Thebuilder pattern encapsulates thelogic of how toput
together a complex object so that the client just requestsa
configuration and the builder directs the logic of building
it.
| The Abstract factorypattern defers the choice of what
concrete type of object tomake.
صفحه 12:
ع رجانه 2ب
Customer Cashier Restaurant Crew
(client) directo (hullden
Order Kia's Meal | پیج
Build
Build
batt
Get Moal
صفحه 13:
Structure
MeaDirecior =| MealBuilder_|
MexcanMeaBuider] —[JapanianMealBuilder|
By
صفحه 14:
Implementation
(Product
faze Meal
«
“public Stringsandwichs
ublieStringsideOrder +
JublieStringdring:
Subliestringoffer
“pubic doubCeprice
_publieStringtoStringd>
3
ای لبماك ماع اهم ماسم ‘return
عماوص ‘Dring sdrinke Price:
2
>
جع ان
1
c
‘public voidadSandwicht)
public voidaddsidedrder0
public voidadabring
public voidserPricet:
“pubic meat getateaC
صفحه 15:
Implementation
iconcreteDuilder ¢
ass JapanianMeat Builder implements Meal Builder
«
‘private Meal meal=new Meal
“public voidaddSandwichi) (meat sandwich="Burger’
‘public voidaddSideOrder’) (meat sideOvder ="Fries )
‘public voidadetDrinkiy (meat rint= Cota’:
“public voidserPricet (meat price 4.992)
‘public Meal get®eat1) (return meal)
2
م ة كلتما مره رز
class MexicanMeaCBuilder implements MeaC Builder
2
‘privateateal meat =new Meat)
public voidaddSandwichi) (meal sandwich ="DoubleBurger'))
‘public voidaddSideOvder') (meat sideOvder = Nachos)
“public voidaddDrinko (meaCdrink= "Peps :)
‘public void set Prices) (meat price=s.49:)
‘public Meat get meat (return meat)
>
۰ Design Pattern
صفحه 16:
Implementation
صفحه 17:
Example 2
O Media may be constructed into different
ations, in this case books, magazines.
represen
newer [ MagazineB wider |
MediaDirector MediaBulder سا
۱ aoe
BookBuilder
Book \ اسيم
ی 4
لعل اد
با
Magazine ۹
]_ هتفه۱
جح
7
Chapter وير
صفحه 18:
Implementation
J! Different representations of media:
class Media extends Arraysist 0
classBookextends Media
class Magazineextends Media 0
// contain different kinds of media items:
class Mediartem (
privatestrings:
public MediartemiStrings) (this.s
publicString toStringy (returns!)
2
class Chapter extends Medialtem (
public Chapter(strings) (super(s):)
>
class Articteextends Medialtem(
public Article strings) (super(s):)
صفحه 19:
Implementation
J ssbut use the same basicconstruction steps:
class MediaBuilder (
public voidbuitaBaser) 0
‘public voidaddMedialtem(Mediartem ite) 0
‘public Media get FinishedMediag) (return null!)
)
class Boot Builder extends Media Builder (
private Book 6:
public voidbuildBaser)(
System.out print(n( Building book framewor®):
ew 00K):
>
PublicvoidadtMediartem(Mediattemchapter? (
System.out primt(nt Adding chapter’ +chapter?:
b.addichapter)
>
public Media get-FinishedMediag) (return 6:)
صفحه 20:
Implementation
builder
Aingmagazineframewart
صفحه 21:
Implementation
public class Buitdmedia ¢
‘publicstaticvoidmain(Stringllargs(
private List input = Arrays.asListinew MediaTtemi](
‘new Mediattem items, new Medialtem(item2,
new Medialtem items), new Medialtem items’),
yi
MediaDirector مان
new MediaDirectorinew BookBuilder())!
buildook.producemedialinput):
String result ='book:" + Book:
System.out printCn(resutt)1//"Booklitems,itemz,items.itemal”
Media boo
MediaDirector fuildMagazin:
new MediaDirector(new MagazineBuilder)):
‘Media magazine - buildMagazine,produceMediatinput
String result ~ ‘magazine: «magazine:
System.out printCnresutt) //’magazineslitems,itema,items items!
صفحه 22:
Thanks
Design Pattern Course
Builder Pattern
By : Sajjad Zare
Teacher : Dr. Noorhosseini
By: Sajjad Zare
Design Pattern
1
Intent
Separate the construction of a complex
object from its representation so that
the same construction process can
create different representations.
By: Sajjad Zare
Design Pattern
2
Example
A reader for the RTF (Rich Text Format)
document be able to convert RTF to many text
formats.
The reader might convert RTF documents into
plain ASCII text or into a text widget that can
be edited interactively.
The problem is that the number of possible
conversions is open-ended. So it should be
easy to add a new conversion without
modifying the reader.
By: Sajjad Zare
Design Pattern
3
while( t = getToken() )
{
switch destinationType
{
ASCII:
//...
WORD:
//...
PDF:
//...
...
}
}
//showConveretedResultRepresentation
By: Sajjad Zare
Design Pattern
4
Solution
Configure the RTFReader class with a
TextConverter object that converts RTF to
another textual representation .
Whenever the RTFReader recognizes an RTF
token , it issues a request to the TextConverter
to convert the token.
TextConverter objects are responsible both for
performing the data conversion and for
representing the token in a particular format.
By: Sajjad Zare
Design Pattern
5
Solution
By: Sajjad Zare
Design Pattern
6
Structure
By: Sajjad Zare
Design Pattern
7
Components in Builder
Pattern
Builder
Abstract interface for creating objects (product).
Concrete Builder
Provide implementation for Builder. Construct and assemble
parts to build the objects.
Director
The Director class is responsible for managing the correct
sequence of object creation. It receives a Concrete Builder
as a parameter and executes the necessary operations on
it.
Product
The final object that will be created by the Director using
Builder.
By: Sajjad Zare
Design Pattern
8
Applicability
The algorithm for creating a complex object
should be independent of the parts that make
up the object and how they're assembled.
The construction process must allow different
representations
for
the
object
that's
constructed.
By: Sajjad Zare
Design Pattern
9
Advantages
Encapsulate the way a complex object is
constructed.
Allows objects to be constructed in a multi-step
processes.
Hides the internal representation of the product
from the client.
Product implementation can be swapped in and
out because the client only sees the abstract
interface.
By: Sajjad Zare
Design Pattern
10
Related Pattern
Abstract Factory
Builder focuses on constructing a complex object
step by step while Abstract Factory emphasizes a
family of product objects
The builder pattern encapsulates the logic of how to
put together a complex object so that the client just
requests a configuration and the builder directs the
logic of building it.
The Abstract factory pattern defers the choice of
what concrete type of object to make.
By: Sajjad Zare
Design Pattern
11
Example 1
By: Sajjad Zare
Design Pattern
12
Structure
By: Sajjad Zare
Design Pattern
13
Implementation
//Product
class Meal
{
public String sandwich ;
public String sideOrder ;
public String drink ;
public String offer ;
public double price ;
}
public String toString()
{
return "Sandwich:"+sandwich+ " SideOrder:"+sideOrder+
" Drink:"+drink+" Price:"+price;
}
//Builder
interface
{
public
public
public
public
public
}
MealBuilder
void addSandwich();
void addSideOrder();
void addDrink();
void setPrice();
Meal getMeal();
By: Sajjad Zare
Design Pattern
14
Implementation
//concreteBuilder 1
class JapanianMealBuilder implements MealBuilder
{
private Meal meal = new Meal();
public
public
public
public
public
void addSandwich() { meal.sandwich = "Burger"; }
void addSideOrder() { meal.sideOrder = "Fries"; }
void addDrink() { meal.drink = "Cola"; }
void setPrice() { meal.price = 4.99; }
Meal getMeal() { return meal; }
}
//concreteBuilder 2
class MexicanMealBuilder implements MealBuilder
{
private Meal meal = new Meal();
public
public
public
public
public
void addSandwich() { meal.sandwich = "DoubleBurger"; }
void addSideOrder() { meal.sideOrder = "Nachos"; }
void addDrink() { meal.drink = "Pepsi"; }
void setPrice() { meal.price = 5.49; }
Meal getMeal() { return meal; }
}
By: Sajjad Zare
Design Pattern
15
Implementation
//Director
class MealDirector
{
public void makeMeal(MealBuilder mealBuilder) {
mealBuilder.addSandwich();
mealBuilder.addSideOrder();
mealBuilder.addDrink();
mealBuilder.setPrice();
}
}
public class MealUse
{
public static void main(String[] args) {
MealDirector director = new MealDirector();
MealBuilder jmb = new JapanianMealBuilder();
director.makeMeal(jmb);
Meal jMeal = jmb.getMeal();
MealBuilder mmb = new MexicanMealBuilder();
director.makeMeal(mmb);
Meal mMeal = mmb.getMeal();
System.out.println(jMeal); //Sandwich:Burger SideOrder:Fries Drink:Cola Price:4.99
System.out.println(mMeal); //Sandwich:DoubleBurger SideOrder:Nachos Drink:Pepsi Price:5.49
}
}
By: Sajjad Zare
Design Pattern
16
Example 2
Media may be constructed into different
representations, in this case books, magazines.
By: Sajjad Zare
Design Pattern
17
Implementation
// Different "representations" of media:
class Media extends ArrayList {}
class Book extends Media {}
class Magazine extends Media {}
// ... contain different kinds of media items:
class MediaItem {
private String s;
public MediaItem(String s) { this.s = s; }
public String toString() { return s; }
}
class Chapter extends MediaItem {
public Chapter(String s) { super(s); }
}
class Article extends MediaItem {
public Article(String s) { super(s); }
}
By: Sajjad Zare
Design Pattern
18
Implementation
// ... but use the same basic construction steps:
class MediaBuilder {
public void buildBase() {}
public void addMediaItem(MediaItem item) {}
public Media getFinishedMedia() { return null; }
}
class BookBuilder extends MediaBuilder {
private Book b;
public void buildBase() {
System.out.println("Building book framework");
b = new Book();
}
public void addMediaItem(MediaItem chapter) {
System.out.println("Adding chapter " + chapter);
b.add(chapter);
}
public Media getFinishedMedia() { return b; }
}
By: Sajjad Zare
Design Pattern
19
Implementation
class MagazineBuilder extends MediaBuilder {
private Magazine m;
public void buildBase() {
System.out.println("Building magazine framework");
m = new Magazine();
}
public void addMediaItem(MediaItem article) {
System.out.println("Adding article " + article);
m.add(article);
}
public Media getFinishedMedia() { return m; }
}
class MediaDirector {
private MediaBuilder mb;
public MediaDirector(MediaBuilder mb) {
this.mb = mb; // buider
}
public Media produceMedia(List input) {
mb.buildBase();
for(Iterator it = input.iterator(); it.hasNext();)
mb.addMediaItem((MediaItem)it.next());
return mb.getFinishedMedia();
}
};
By: Sajjad Zare
Design Pattern
20
Implementation
public class BuildMedia {
public static void main(String[] args){
private List input = Arrays.asList(new MediaItem[] {
new MediaItem("item1"), new MediaItem("item2"),
new MediaItem("item3"), new MediaItem("item4"),
});
MediaDirector buildBook =
new MediaDirector(new BookBuilder());
Media book = buildBook.produceMedia(input);
String result = "book: " + book;
System.out.println(result);//"book: [item1, item2, item3, item4]“
MediaDirector buildMagazine =
new MediaDirector(new MagazineBuilder());
Media magazine = buildMagazine.produceMedia(input);
String result = "magazine: " + magazine;
System.out.println(result); //"magazine: [item1, item2, item3, item4]“
}
}
By: Sajjad Zare
Design Pattern
21
Thanks
By: Sajjad Zare
Design Pattern
22