interface Document {
    void open();
    void close();
}

class PdfDocument implements Document {
    public void open() {
        System.out.println("Opening PDF...");
    }
    public void close() {
        System.out.println("Closing PDF...");
    }
}

class WordDocument implements Document {
    public void open() {
        System.out.println("Opening Word...");
    }
    public void close() {
        System.out.println("Closing Word...");
    }
}

abstract class DocumentFactory {
    public abstract Document createDocument();

    public void process() {
        Document doc = createDocument();
        doc.open();
        // do work
        doc.close();
    }
}

class PdfFactory extends DocumentFactory {
    public Document createDocument() {
        return new PdfDocument();
    }
}

class WordFactory extends DocumentFactory {
    public Document createDocument() {
        return new WordDocument();
    }
}

public static void main(String[] args) {
    DocumentFactory factory = new PdfFactory();
    factory.process();
}
Back to Design Patterns
Creational Design Pattern

Factory Method

The Factory Method pattern defines an interface for creating an object but lets subclasses alter the type of objects that will be created. It promotes loose coupling by eliminating the need to bind application-specific classes into the code. The pattern is especially useful when a class cannot anticipate the class of objects it must create, or when a class wants its subclasses to specify the objects it creates.