Learning the Abstract Factory Pattern: Implementing It

Example 10-3 shows how to implement the Abstract Factory objects for this design.

Example 10-3. Java Code Fragments: Implementation of ResFactory
abstract class ResFactory {
  abstract public DisplayDriver getDispDrvr();
  abstract public PrintDriver getPrtDrvr();
}

class LowResFact extends ResFactory {
  public DisplayDriver getDispDrvr() {
    return new LRDD();
  }
  public PrintDriver getPrtDrvr() {
    return new LRPD();
  }
}

class HighResFact extends ResFactory {
  public DisplayDriver getDispDrvr() {
    return new HRDD();
  }
  public PrintDriver getPrtDrvr() {
    return new HRPD();
  }
}

To finish the solution, I have the ApControl talk with the appropriate factory object (either LowResFact or HighResFact); this is shown in Figure 10-6. Note that ResFactory is abstract, and that this hiding of ResFactory's implementation is what makes the pattern work. Hence, the name Abstract Factory for the pattern.

Figure 10-6. Intermediate solution using the Abstract Factory.


ApControl is given either a LowResFact object or a HighResFact object. It asks this object for the appropriate drivers when it needs them. The factory object instantiates the particular driver (low or high resolution) that it knows about. ApControl does not need to worry about whether a low-resolution or a high-resolution driver is returned since it uses both in the same manner.

I have ignored one issue: LRDD and HRDD may not have been derived from the same abstract class (as may be true of LRPD and HRPD). Knowing the Adapter pattern, this does not present much of a problem. I can simply use the structure I have in Figure 10-6, but adapt the drivers as shown in Figure 10-7.

Figure 10-7. Solving the problem with the Abstract Factory and Adapter.


The implementation of this design is essentially the same as the one before it. The only difference is that now the factory objects instantiate objects from classes I have created that adapt the objects I started with. This is an important modeling method. By combining the Adapter pattern with the Abstract Factory pattern in this way, I can treat these conceptually similar objects as if they were siblings even if they are not. This enables the Abstract Factory to be used in more situations.

In this pattern,

  • The client object just knows who to ask for the objects it needs and how to use them.

  • The Abstract Factory class specifies which objects can be instantiated by defining a method for each of these different types of objects. Typically, an Abstract Factory object will have a method for each type of object that must be instantiated.

  • The concrete factories specify which objects are to be instantiated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset