简单工厂模式

模式意图

我们希望在创建一个对象时,通过传递不同的参数而得到不同的对象。我们不需要知道对象创建的具体细节。从而,客户端在使用时只需要传递相应的参数,即可获取到对象。

简单工厂模式(Simple Factory Pattern):又称为静态工厂方法(Static Factory Method)模式,它属于类创建型模式。在简单工厂模式中,可以根据参数的不同返回不同类的实例。简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。

模式应用场景

  • 当一组对象都实现同一个接口时,我们可以使用简单工厂模式来创建对象。

    具体实例

    假设有几种武器SpearBowAxeSword 都实现了 Weapon 接口,并且每个武器内部都有自己的不同实现。我们可以使用一个 WeaponFactory 来创造这些武器,客户端只需要传递相应的武器类型即可。类之间的关系图如下图所示。
    简单工厂模式类图
    具体代码如下:
    武器接口以及各种武器的具体实现:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    /**
    * Interface representing weapon.
    */
    public interface Weapon {
    }
    /**
    * Class representing Axe
    */
    public class Axe implements Weapon {
    @Override
    public String toString() {
    return "Axe";
    }
    }
    /**
    * Class representing Bows
    */
    public class Bow implements Weapon {
    @Override
    public String toString() {
    return "Bow";
    }
    }
    /**
    * Class representing Spear
    */
    public class Spear implements Weapon {
    @Override
    public String toString() {
    return "Spear";
    }
    }
    /**
    * Class representing Swords
    */
    public class Sword implements Weapon {
    @Override
    public String toString() {
    return "Sword";
    }
    }

WeaponFactory 的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class WeaponFactory
{
private WeaponFactory()
{
}

public static Weapon create(WeaponType type)
{
Weapon weapon = null;
switch (type)
{
case SWORD:
weapon = new Sword();
break;
case AXE:
weapon = new Axe();
break;
case BOW:
weapon = new Bow();
break;
case SPEAR:
weapon = new Spear();
break;
}
return weapon;
}
}

测试代码:

1
2
3
4
public static void main(String[] args) {
Weapon axe = WeaponFactory.create(WeaponType.AXE);
LOGGER.info(axe.toString());
}

运行结果:

1
19:48:38.921 [main] INFO com.iluwatar.factorykit.App - Axe