The Abstract Factory pattern is one level of abstraction higher than
the factory pattern. You can use this pattern when you want to return one of
several related classes of objects, each of which can return several different
objects on request. In other words, the Abstract Factory is a factory object
that returns one of several factories.
Forexample,one classic application of the abstract factory is the case where your
system needs to support multiple “look-and-feel” user interfaces, such as
Windows-9x, Motif or Macintosh. You tell the factory that you want your
program to look like Windows and it returns a GUI factory which returns
Windows-like objects. Then when you request specific objects such as
buttons, check boxes and windows, the GUI factory returns Windows
instances of these visual interface components.
One of the main purposes of the Abstract Factory is that it isolates the
concrete classes that are generated. The actual class names of these classes
are hidden in the factory and need not be known at the client level at all.
Because of the isolation of classes, you can change or interchange
these product class families freely. Further, since you generate only one kind
of concrete class, this system keeps you for inadvertently using classes from
different families of products. However, it is some effort to add new class
families, since you need to define new, unambiguous conditions that cause
such a new family of classes to be returned.
While all of the classes that the Abstract Factory generates have the
same basclass, there is nothing to prevent some derived classes from having
additional methods that differ from the methods of other classes. For example
a BonsaiGarden class might have a Height or WateringFrequency method that
is not present in other classes. This presents the same problem as occur in any
derived classes-- you don’t know whether you can call a class method unless
you know whether the derived class is one that allows those methods. This
problem has the same two solutions as in any similar case: you can either
define all of the methods in the base class, even if they don’t always have a
actual function, or you can test to see which kind of class you have:
if (gard instanceof BonsaiGarden)
int h = gard.Height();
关键点
Abstract Factory有比Factory Method更深一层次的抽象
FM关注于生产 那一种 产品,而AF关注于生产 那一品牌 的 那一种 产品
就像例子里说的,如果是FM,只会在需要的时候选择创建一个 窗口 还是创建一个 按钮,而AF则
选择创建java风格的窗口 或者 按钮 还是创建 windows风格的窗口或者按钮