Use the Factory Pattern

Problem

You want the ability to create classes generically, without knowing their specific types.

Solution

Create a dedicated factory class that can construct the type of class you need.

Discussion

The factory pattern is one of the best-known creational patterns. It provides an abstracted mechanism for creating classes.

In the factory pattern, as shown in Figure 4-4, every class has its own corresponding factory class. In order for the factory pattern to work, all of these classes must derive from two abstract base classes.

The abstract factory pattern

Figure 4-4. The abstract factory pattern

For example, imagine you want to create a generic component that queries ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.