定義
“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.”(在基類中定義創(chuàng)建對象的一個接口,讓子類決定實例化哪個類。工廠方法讓一個類的實例化延遲到子類中進行。)
- 簡單工廠(Simple Factory)模式,又稱靜態(tài)工廠方法模式(Static Factory Method Pattern)。
- 工廠方法(Factory Method)模式,又稱多態(tài)性工廠(Polymorphic Factory)模式或虛擬構(gòu)造子(Virtual Constructor)模式;
- 抽象工廠(Abstract Factory)模式,又稱工具箱(Kit 或Toolkit)模式。
為什么要用工廠模式
- 解耦 :把對象的創(chuàng)建和使用的過程分開;
- 降低代碼重復(fù): 如果創(chuàng)建某個對象的過程都很復(fù)雜,需要一定的代碼量,而且很多地方都要用到,那么就會有很多的重復(fù)代碼。
- 降低維護成本 :由于創(chuàng)建過程都Simple Factory)
創(chuàng)建圖形實例:
首先是圖形接口
public interface Shape {
void draw();
}
創(chuàng)建實現(xiàn)類
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("draw a circle");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("draw an Rectangle");
}
}
創(chuàng)建圖形工廠
public class Factory {
public static Shape getShape(Class<? extends Shape> clazz){
Shape shape = null;
try {
shape = (Shape) Class.forName(clazz.getName()).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return shape;
}
}
測試類
public class Test {
public static void main(String[] args) {
Shape circle = Factory.getShape(Circle.class);
circle.draw();
Shape rectangle = Factory.getShape(Rectangle.class);
rectangle.draw();
}
}
輸出
draw a circle
draw an Rectangle
工廠方法(Factory Method)
工廠方法模式是簡單工廠的僅一步深化, 在工廠方法模式中,我們不再提供一個統(tǒng)一的工廠類來創(chuàng)建所有的對象,而是針對不同的對象提供不同的工廠。也就是說 每個對象都有一個與之對應(yīng)的工廠 。工廠方法模式應(yīng)該是在工廠模式家族中是用的最多模式,一般項目中存在最多的就是這個模式。
創(chuàng)建工廠接口
public interface Factory {
Shape getShape();
}
圓形工廠
public class CircleFactory implements Factory {
@Override
public Shape getShape() {
return new Circle();
}
}
測試類
public class Test {
public static void main(String[] args) {
CircleFactory factory = new CircleFactory();
Shape circle = factory.getShape();
circle.draw();
}
}
抽象工廠(Abstract Factory)
在工廠方法模式中,其實我們有一個潛在意識的意識。那就是我們生產(chǎn)的都是同一類產(chǎn)品。抽象工廠模式是工廠方法的僅一步深化,在這個模式中的工廠類不單單可以創(chuàng)建一種產(chǎn)品,而是可以創(chuàng)建一組產(chǎn)品。
創(chuàng)建抽象類
public interface Animal {
public void catching();
}
public interface Food {
public void cook();
}
創(chuàng)建實體類
public class Cattle implements Animal {
@Override
public void catching() {
System.out.println("catching cattle...");
}
}
public class Beef implements Food {
@Override
public void cook() {
System.out.println("cooking beef...");
}
}
創(chuàng)建工廠接口
public interface Factory {
Food getFood();
Animal catchingAnimal();
}
創(chuàng)建牛肉工廠
public class BeefFactroy implements Factory {
@Override
public Food getFood() {
return new Beef();
}
@Override
public Animal catchingAnimal() {
return new Cattle();
}
}
測試類
public class Test {
public static void main(String[] args) {
Factory AKFactory = new BeefFactroy();
Animal bullet = AKFactory.catchingAnimal();
Food food = AKFactory.getFood();
bullet.catching();
food.cook();
}
}
輸出
catching cattle...
cooking beef...