《设计模式解析》 第23章 Factory Method 模式 复习题

来源:互联网 发布:基础编程学习 编辑:程序博客网 时间:2024/05/17 09:21

《设计模式解析》 第23章 Factory Method 模式

Review Questions

Observation

1:

What are factories responsible for?

工厂负责对象的创建以及管理或者包括一些错误处理。

2:

What is the essential reason to use the Factory Method?

需要将对象的初始化延迟到子类中的情况。

3:

The Factory Method pattern has been implemented in all of the major object-oriented languages. How has it been provided for in Java, C#, and C++?

集中的抽象类中,有protect方法:createIterator(),用于让子类(List,vector,Composite)实现,来获取相应的Iterator。

Interpretation

1:

Why is this pattern called the "Factory Method"?

工厂方法,功能是创建相应的对象,并提供一个方法,让外界无需理会不同对象的不同创建方式。

2:

How does the Factory Method pattern fit in with other factories?

抽象工厂模式用于对象创建的解耦。但二者配合时,就是抽象工厂的抽象类中,有需要延迟创建的对象,则可以将二者结合。

3:

The Gang of Four says that the intent of the Factory Method is to "define an interface for creating an object, but let subclasses decide which class to instantiate." Why is this important?

父类中,某一些使用的对象可能有多种不同的实现方式。而在父类中无法确定这些对象具体如何初始化(需要根据派生类的功能,才能够确定),因此,将该对象的初始化延迟到派生类理所当然。

这种方式,可以使得在父类中进行一些操作的实现,而当具体的操作对象改变时,父类无需改变,因为父类持有的是对象的超类而非具体实现。

Opinion and Application

1:

How should you go about deciding whether a method should be public, private, or protected?

Protected的时候,一般是在父类需要调用该方法,而不同的子类可能有其自己的实现,使之能够重写该方法,或者能够调用该父类的方法。但不希望外界进行调用。

2:

This is a short chapter but this is not a trivial pattern. Think of one example where this pattern could be used.

五子棋中,AbstractBoard作为棋盘的抽象类,有五子棋、象棋…的棋盘,而里面又有五子棋、象棋…的棋子,故可以用工厂模式,在AbstractBoard中持有棋子的抽象类来操作棋子,将实例化延迟到具体的棋盘中…