簡單工廠模式
簡單工廠模式是類的創建模式,又叫靜態工廠方法模式,它由一個工廠對象決定創建出哪一種產品類的實例。工廠模式專門負責將大量有共同接口的類實例化,可以動態決定將哪一個類實例化,不必事先知道每次要實例化的是哪一個類
?
簡單工廠模式的核心是工廠類,它含有必要的判斷邏輯,可以決定在什么時候創建哪一個產品類的實例。簡單工廠模式一般只有一個工廠方法,如下圖的
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("不能創建這樣的對象");
}?
}?
??
public
?
interface
?Art{?
???????
public
?
void
?draw();?
???????
public
?
void
?erase();?
}?
??
public
?
class
?Round?
implements
?Art{?
???????
public
?
void
?draw(){?
??????????????System.out.println(“畫一個圓形”);?
}?
public
?
void
?erase(){?
???????System.out.println(“刪除一個圓形”);?
}?
}?
??
public
?
class
?Square?
implements
?Art{?
???????
public
?
void
?draw(){?
??????????????System.out.println(“畫一個方形”);?
}?
public
?
void
?erase(){?
???????System.out.println(“刪除一個方形”);?
}?
}?
??
public
?
class
?Triangle?
implements
?Art{?
???????
public
?
void
?draw(){?
??????????????System.out.println(“畫一個三角形”);?
}?
public
?
void
?erase(){?
???????System.out.println(“刪除一個三角形”);?
}?
}?
??
public
?
class
?Main{?
???????
public
?
static
?
void
?main(String[]?args){?
??????????????Art?art?
=
?Factory.factory(“圓形”);?
??????????????art.draw();?
}?
}?
三種角色:
?????????工廠類角色:是簡單工廠方法模式的核心,含有與應用緊密聯系的邏輯。
?????????抽象產品
?????????具體產品