目的:
为创建一个对象定义一个接口,但是让子类决定实例化哪个类。工厂方法允许类将实例化延迟到子类。
程序示例:
铁匠生产武器。精灵需要精灵武器,而兽人需要兽人武器。根据客户来召唤正确类型的铁匠。
1.创建武器接口和类型
public interface Weapon{
WeaponType getWeaponType();
}
//类型
@RequiredArgsConstructor
public enum WeaponType {
SHORT_SWORD("short sword"),
SPEAR("spear"),
AXE("axe"),
UNDEFINED("");
private final String title;
@Override
public String toString() {
return title;
}
}
2.武器实现
@RequiredArgsConstructor
@Getter
public class ElfWeapon implements Weapon {
private final WeaponType weaponType;
@Override
public String toString() {
return "an elven " + weaponType;
}
}
@RequiredArgsConstructor
@Getter
public class OrcWeapon implements Weapon {
private final WeaponType weaponType;
@Override
public String toString() {
return "an orcish " + weaponType;
}
}
3.生产者接口及其子类(工厂方法的精髓)
public interface Blacksmith{
Weapon manufactureWeapon(WeaponType type);
}
public class ElfBlacksmith implements Blacksmith{
private static final Map<WeaponType,ElfWeapon> ELFARSENAl;
static {
ELFARSENAl=new EnumMap<WeaponType,ElfWeapon>(WeaponType.class);
Arrays.stream(WeaponType.values()).forEach(type -> ELFARSENAl.put(type,new ElfWeapon(type)));
}
@Override
public Weapon manufactureWeapon(WeaponType type) {
return ELFARSENAl.get(type);
}
@Override
public String toString() {
return "The elf blacksmith";
}
}
public class OrcBlacksmith implements Blacksmith{
private static final Map<WeaponType,OrcWeapon> ORCARSENAL;
static {
ORCARSENAL=new EnumMap<WeaponType,OrcWeapon>(WeaponType.class);
Arrays.stream(WeaponType.values()).forEach(type -> ORCARSENAL.put(type,new OrcWeapon(type)));
}
@Override
public Weapon manufactureWeapon(WeaponType type) {
return ORCARSENAL.get(type);
}
@Override
public String toString() {
return "The orc Blacksmith";
}
}
测试输出
OrcBlacksmith orcBlacksmith = new OrcBlacksmith();
Weapon orcWeapon = orcBlacksmith.manufactureWeapon(WeaponType.SPEAR);
log.info(MANUFACTURED, orcBlacksmith, orcWeapon);
orcWeapon = orcBlacksmith.manufactureWeapon(WeaponType.AXE);
log.info(MANUFACTURED, orcBlacksmith, orcWeapon);
/*
The orc Blacksmith manufactured an orcish spear
The orc Blacksmith manufactured an orcish axe
*/
ElfBlacksmith elfBlacksmith = new ElfBlacksmith();
Weapon weapon = elfBlacksmith.manufactureWeapon(WeaponType.SHORT_SWORD);
log.info(MANUFACTURED, elfBlacksmith,weapon);
weapon=elfBlacksmith.manufactureWeapon(WeaponType.AXE);
log.info(MANUFACTURED, elfBlacksmith,weapon);
/*
The elf blacksmith manufactured an elven short_sword
The elf blacksmith manufactured an elven axe
*/
类图: