簡(jiǎn)單工廠模式
簡(jiǎn)單工廠模式是類的創(chuàng)建模式,又叫靜態(tài)工廠方法模式,它由一個(gè)工廠對(duì)象決定創(chuàng)建出哪一種產(chǎn)品類的實(shí)例。工廠模式專門負(fù)責(zé)將大量有共同接口的類實(shí)例化,可以動(dòng)態(tài)決定將哪一個(gè)類實(shí)例化,不必事先知道每次要實(shí)例化的是哪一個(gè)類
?
簡(jiǎn)單工廠模式的核心是工廠類,它含有必要的判斷邏輯,可以決定在什么時(shí)候創(chuàng)建哪一個(gè)產(chǎn)品類的實(shí)例。簡(jiǎn)單工廠模式一般只有一個(gè)工廠方法,如下圖的
Factory
類的
factory()
方法。
?
例:
public
?
class
?Factory{?
??????????????
public
?Factory(){}?
??????????????
public
?
static
?art?factory(String?art){?
?????????????????????
if
(art.equals(“圓形”))?
????????????????????????????
return
?
new
?Round();?
?????????????????????
else
?
if
(art.equals(“方形”))?
????????????????????????????
return
?
new
?Square();?
?????????????????????
else
?
if
(art.equals(“三角形”))?
????????????????????????????
return
?
new
?Triangle();?
?????????????????????else?
??????????????????????????throw new? Exception("不能創(chuàng)建這樣的對(duì)象");
}?
}?
??
public
?
interface
?Art{?
???????
public
?
void
?draw();?
???????
public
?
void
?erase();?
}?
??
public
?
class
?Round?
implements
?Art{?
???????
public
?
void
?draw(){?
??????????????System.out.println(“畫一個(gè)圓形”);?
}?
public
?
void
?erase(){?
???????System.out.println(“刪除一個(gè)圓形”);?
}?
}?
??
public
?
class
?Square?
implements
?Art{?
???????
public
?
void
?draw(){?
??????????????System.out.println(“畫一個(gè)方形”);?
}?
public
?
void
?erase(){?
???????System.out.println(“刪除一個(gè)方形”);?
}?
}?
??
public
?
class
?Triangle?
implements
?Art{?
???????
public
?
void
?draw(){?
??????????????System.out.println(“畫一個(gè)三角形”);?
}?
public
?
void
?erase(){?
???????System.out.println(“刪除一個(gè)三角形”);?
}?
}?
??
public
?
class
?Main{?
???????
public
?
static
?
void
?main(String[]?args){?
??????????????Art?art?
=
?Factory.factory(“圓形”);?
??????????????art.draw();?
}?
}?
三種角色:
?????????工廠類角色:是簡(jiǎn)單工廠方法模式的核心,含有與應(yīng)用緊密聯(lián)系的邏輯。
?????????抽象產(chǎn)品
?????????具體產(chǎn)品