什么时候在对象中使用工厂方法而不是factory类是一个好主意?
当前回答
任何将对象创建延迟到其需要使用的对象的子类的类都可以视为Factory模式的示例。
我在https://stackoverflow.com/a/49110001/504133的另一个回答中详细提到过
其他回答
我认为这取决于你想要给你的代码带来的松耦合程度。
工厂方法解耦得很好,但是工厂类不行。
换句话说,使用工厂方法比使用简单的工厂(称为工厂类)更容易更改内容。
看看这个例子:https://connected2know.com/programming/java-factory-pattern/。现在,想象一下你想要带来一个新的动物。在Factory类中,您需要更改Factory,但在Factory方法中,不需要,您只需要添加一个新的子类。
任何将对象创建延迟到其需要使用的对象的子类的类都可以视为Factory模式的示例。
我在https://stackoverflow.com/a/49110001/504133的另一个回答中详细提到过
如果你想在使用方面创建一个不同的对象。它很有用。
public class factoryMethodPattern {
static String planName = "COMMERCIALPLAN";
static int units = 3;
public static void main(String args[]) {
GetPlanFactory planFactory = new GetPlanFactory();
Plan p = planFactory.getPlan(planName);
System.out.print("Bill amount for " + planName + " of " + units
+ " units is: ");
p.getRate();
p.calculateBill(units);
}
}
abstract class Plan {
protected double rate;
abstract void getRate();
public void calculateBill(int units) {
System.out.println(units * rate);
}
}
class DomesticPlan extends Plan {
// @override
public void getRate() {
rate = 3.50;
}
}
class CommercialPlan extends Plan {
// @override
public void getRate() {
rate = 7.50;
}
}
class InstitutionalPlan extends Plan {
// @override
public void getRate() {
rate = 5.50;
}
}
class GetPlanFactory {
// use getPlan method to get object of type Plan
public Plan getPlan(String planType) {
if (planType == null) {
return null;
}
if (planType.equalsIgnoreCase("DOMESTICPLAN")) {
return new DomesticPlan();
} else if (planType.equalsIgnoreCase("COMMERCIALPLAN")) {
return new CommercialPlan();
} else if (planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {
return new InstitutionalPlan();
}
return null;
}
}
这真的是个品味问题。工厂类可以根据需要进行抽象/接口,而工厂方法是轻量级的(而且往往是可测试的,因为它们没有定义的类型,但它们需要一个众所周知的注册点,类似于服务定位器,但用于定位工厂方法)。
当您需要几个具有相同参数类型但具有不同行为的“构造函数”时,它们也很有用。