我一直在阅读头第一:设计模式一书,我发现这本书是对设计模式的一个很好的介绍。然而,关于他们在第四章中提出的一个主张,我有一个问题:
他们将“简单工厂”模式定义如下(Java伪代码):
public abstract class Product
{
// Product characteristics
// Concrete Products should subclass this
}
public class SimpleFactory {
public Product createProduct(){
// Return an instance of some subclass of Product
}
}
public class Store {
SimpleFactory factory;
public Product orderProduct(){
Product product = factory.createProduct();
// Do some manipulation on product
return product;
}
}"Factory方法“的定义如下(产品类保持不变,省略):
public abstract class Store {
//Concrete Stores must subclass this and override createProduct()
public abstract Product createProduct();
public Product orderProduct(){
Product product = createProduct();
// Do some manipulation on product
return product;
}
}然后,作者继续声称Factory方法模式比Simple灵活得多,因为当Simple是“一发交易,使用Factory方法时,您正在创建一个框架,让子类决定应该使用哪个实现”(第135页)。
现在我不明白为什么这是真的。在我看来,Simple在某种意义上比Factory方法稍微灵活一些:您可以对Simple进行子类(而不是子类),以获得本质上相同的行为。如果您愿意,甚至可以在运行时更改行为!简单工厂的唯一缺点是,当产品创建依赖于Store类的状态变量时:这是作者所称的灵活性,还是我遗漏了什么?
发布于 2014-10-22 16:04:10
您完全正确:作者的假设是,您不会使用SimpleFactory子类,这是一个不公平的假设(除非SimpleFactory标记为final)。
由于SimpleFactory不是最终的,所以您肯定可以对它进行子类处理,这样可以获得比工厂方法更大的灵活性,因为SimpleFactory用组合代替继承。
一个更好的方法是使SimpleFactory成为一个接口。这样做可以让您根据自己的喜好选择组合或继承,因为在Store类已经继承了类的情况下,接口不会限制您。
public interface SimpleFactory {
Product createProduct();
}然后你可以使用任何一种构图
public class FactoryImpl implements SimpleFactory {
public Product createProduct(){
// Return an instance of some subclass of Product
}
}
public class StoreComposition {
SimpleFactory factory = new FactoryImpl();
}或继承/组合组合
public class StoreInheritance implements SimpleFactory {
SimpleFactory factory = this;
public Product createProduct(){
// Return an instance of some subclass of Product
}
}发布于 2019-12-26 04:03:01
在Simple Factory中,您编写了一个类,它提供了非常强大的封装功能,但是只需要做一件事:封装对象的创建和底层类型。而工厂方法模式充分利用了这个类的优势:它做简单工厂所做的事情,除了之外,它还封装了创建过程,不仅创建了一个“原始的新对象”,而且还创建了一个可交付/设备齐全的结果,这就是为什么它称orderProduct而不仅仅是createProduct。
简而言之,Factory方法的要点是使用简单工厂的方法。所以,如果您认为Factory方法不那么灵活,那是因为Factory方法做了更多的事情!
https://stackoverflow.com/questions/26511823
复制相似问题