簡(jiǎn)單工廠模式
簡(jiǎn)單工廠模式又叫做靜態(tài)工廠方法模式。由一個(gè)工廠對(duì)象根據(jù)傳入的參數(shù)決定創(chuàng)建哪一種產(chǎn)品(類)的實(shí)例。簡(jiǎn)單工廠模式隱藏了對(duì)象的創(chuàng)建邏輯,調(diào)用者只需知道它們共同的接口是是什么,從而使軟件的結(jié)構(gòu)更加清晰,整個(gè)系統(tǒng)的設(shè)計(jì)也更符合單一職責(zé)原則。
簡(jiǎn)單工廠模式的角色以及對(duì)應(yīng)的職責(zé):
-
工廠(Creator)
簡(jiǎn)單工廠模式的核心,它負(fù)責(zé)實(shí)現(xiàn)創(chuàng)建所有實(shí)例的內(nèi)部邏輯。工廠類的創(chuàng)建產(chǎn)品類的方法可以被外界直接調(diào)用,創(chuàng)建所需的產(chǎn)品對(duì)象。
-
抽象產(chǎn)品(Product)
簡(jiǎn)單工廠模式所創(chuàng)建的所有對(duì)象的父類,它負(fù)責(zé)描述所有實(shí)例所共有的公共接口。
-
具體產(chǎn)品(Concrete Product)
是簡(jiǎn)單工廠模式的創(chuàng)建目標(biāo),所有創(chuàng)建的對(duì)象都是這個(gè)角色的某個(gè)具體類的實(shí)例。
什么時(shí)候使用
簡(jiǎn)單工廠模式可以根據(jù)傳入的參數(shù)實(shí)例化相應(yīng)的對(duì)象,適用于以下情景:
- 使用對(duì)象的調(diào)用者只關(guān)心需要的參數(shù),不關(guān)心對(duì)象如何被創(chuàng)建,甚至不需要知道對(duì)象的名字
- 創(chuàng)建邏輯復(fù)雜的類
- 解耦一系列相似對(duì)象的創(chuàng)建
一個(gè)簡(jiǎn)單的例子
抽象產(chǎn)品的定義
在這里,我們定義一個(gè)Shape:
public interface Shape {
void draw();
}
具體產(chǎn)品的定義
在這里,我們定義了Shape的三個(gè)實(shí)現(xiàn)類Rectangle、Square和Circle,它們分別有各自的實(shí)現(xiàn)的draw()方法:
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
工廠的定義
ShapeFactory可以根據(jù)傳入的shapeType返回對(duì)應(yīng)的Shape實(shí)現(xiàn)類
public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
使用:
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw method of Circle
shape1.draw();
//get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//call draw method of Rectangle
shape2.draw();
//get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");
//call draw method of square
shape3.draw();
}
}