Factory Method Pattern Demo

package FactoryMethodPattern; public interface Document { void open(); }
package FactoryMethodPattern; public class PdfDocument implements Document { public void open() { System.out.println("Opening PDF document..."); } }
package FactoryMethodPattern; // Concrete products public class WordDocument implements Document { public void open() { System.out.println("Opening Word document..."); } }

Driver

Let's take the example of a Document Management System, where you can create different types of documents, like Word documents, PDFs, Excel files, etc.

In this example, the Document interface represents the abstract product. The WordDocument and PdfDocument classes are concrete products.

The DocumentFactory class is the abstract creator that declares the factory method createDocument(). The WordDocumentFactory and PdfDocumentFactory classes are concrete creators that implement createDocument() to produce WordDocument and PdfDocument instances respectively.

This design allows adding new types of documents in the system by simply adding a new factory class and a new document class, without modifying the existing code. The client code can work with any document type, depending on the factory it is provided with. This encapsulates the process of object creation and reduces direct dependencies between classes.