是否真的应该只在创建新对象时才使用工厂,需要考虑到以前的对象、工厂内部变量和外部变量?
我举个例子:
interface Zone{
Enemy toCreate(String name);
}
class Zone101 implements Zone{
final int enemyToIncreaseTheirDifficult = 3;
int countOfCreatedEnemies = 0;
int difficult = 0;
public Enemy toCreate(String name) {
if(name.equals("Zombie")) {
if(countOfCreatedEnemies % enemyToIncreaseTheirDifficult == 0) {
difficult++;
}
countOfCreatedEnemies++;
return new Zombie(difficult);
}else {
return null;
}
}
}
class Enemy{
private int difficult;
Enemy(int difficult){
this.difficult = difficult;
}
}
class Zombie extends Enemy{
int timesToReLife;
Zombie(int difficult){
super(difficult);
timesToReLife = difficult + 1;
}
}
该措辞并未涵盖所有情况。
当我们需要为类 A 的构造函数添加一些新的逻辑时,也需要工厂,我们不必对类 A 进行更改——添加构造函数或创建 toCreate 方法。创建一个工厂就足够了。