DEV Community

Discussion on: Understanding the Factory Method Design Pattern

Collapse
 
bilelsalemdev profile image
bilel salem • Edited

Here is a detailed explanation why Abstract Classes are not same as Factory Method Pattern

Feature Abstract Classes Factory Method Pattern
Purpose Define common behavior and enforce method implementation in subclasses. Encapsulate object creation and allow subclasses to determine the concrete class to instantiate.
Usage When you want to define a common interface and shared behavior among a group of related classes. When the creation process is complex, varies between subclasses, or should be decoupled from client code.
Polymorphism Yes, allows different subclasses to be treated uniformly. Yes, but focuses on the creation process being polymorphic.
Code Reuse Allows code reuse by defining common methods in the abstract class. Separates creation logic from the business logic, allowing reuse of the creation process.
Encapsulation Encapsulates common behavior and properties of subclasses. Encapsulates object creation logic, making it easier to manage and change.
Client Code Needs to know the specific subclass to instantiate. Decoupled from concrete classes, only interacts with abstract creator and product interfaces.
Flexibility Limited to defining behavior and properties; does not handle instantiation flexibility. High, as it allows subclasses to change the class of objects that will be created without modifying the client code.
Extensibility Adding new behavior requires modifying the abstract class or existing subclasses. Adding new products requires creating new creator subclasses, without modifying existing client code.
Instantiation Direct instantiation of subclasses, leading to tighter coupling between client code and concrete classes. Uses a factory method to create objects, promoting loose coupling and adherence to the Open/Closed Principle.

Example Abstract Class in TypeScript

abstract class Document {
    abstract open(): void;
    abstract save(): void;
    abstract close(): void;

    print(): void {
        console.log("Printing document");
    }
}

class WordDocument extends Document {
    open(): void {
        console.log("Opening Word Document");
    }
    save(): void {
        console.log("Saving Word Document");
    }
    close(): void {
        console.log("Closing Word Document");
    }
}

class PDFDocument extends Document {
    open(): void {
        console.log("Opening PDF Document");
    }
    save(): void {
        console.log("Saving PDF Document");
    }
    close(): void {
        console.log("Closing PDF Document");
    }
}

// Client code
function processDocument(doc: Document) {
    doc.open();
    doc.save();
    doc.close();
    doc.print();
}

const wordDoc: Document = new WordDocument();
processDocument(wordDoc);

const pdfDoc: Document = new PDFDocument();
processDocument(pdfDoc);
Enter fullscreen mode Exit fullscreen mode

Example Factory Method Pattern in TypeScript

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

class WordDocument implements Document {
    open(): void {
        console.log("Opening Word Document");
    }
    save(): void {
        console.log("Saving Word Document");
    }
    close(): void {
        console.log("Closing Word Document");
    }
}

class PDFDocument implements Document {
    open(): void {
        console.log("Opening PDF Document");
    }
    save(): void {
        console.log("Saving PDF Document");
    }
    close(): void {
        console.log("Closing PDF Document");
    }
}

abstract class DocumentCreator {
    public abstract createDocument(): Document;

    public newDocument(): void {
        const doc = this.createDocument();
        doc.open();
        doc.save();
        doc.close();
    }
}

class WordDocumentCreator extends DocumentCreator {
    public createDocument(): Document {
        return new WordDocument();
    }
}

class PDFDocumentCreator extends DocumentCreator {
    public createDocument(): Document {
        return new PDFDocument();
    }
}

// Client code
class Application {
    public static main(): void {
        let creator: DocumentCreator;

        creator = new WordDocumentCreator();
        creator.newDocument();

        creator = new PDFDocumentCreator();
        creator.newDocument();
    }
}

Application.main();
Enter fullscreen mode Exit fullscreen mode

By using this table and examples, you can see how abstract classes and the Factory Method pattern serve different purposes and how they can complement each other .

Collapse
 
efpage profile image
Eckehard • Edited

Thank you much for your detailed explanation. Maybe this goes beyond the tasks I commonly used classes for. I just have still some questions:

Why did you not add newDocument to the abstract class like we would commonly do (this is JS syntax)? Isn´t this the task of an abstract class?

class Document {
    constructor(){ ... }
    open(){ ... };
    save(){ ... };
    close(){ ... };
    newDocument(): void {
        this.open();
        this.save();
        this.close();
    }
}
class WordDocument extends Document { ... }

creator = new WordDocument();
creator.newDocument();
Enter fullscreen mode Exit fullscreen mode

Did you use ChatGPT for the examples, as the code seems to have some issuses?

    public newDocument(): void {
        const doc = this.createDocument();
        doc.open();
        doc.save();
        doc.close();
        return doc; // <== missing
    }
Enter fullscreen mode Exit fullscreen mode

newDocument does not work without actually returning the document

        let creator: DocumentCreator;

        creator = new WordDocumentCreator();
        creator.newDocument();

        creator = new PDFDocumentCreator();  // prevent access access to the WordDocument without removing the instance? 
        creator.newDocument();

Enter fullscreen mode Exit fullscreen mode

In my understanding assigning a new object to creator will override the accessor without removing the instance, so you will have no access to the object anymore and get a memory leak.

Or did I get something wrong?

Thread Thread
 
bilelsalemdev profile image
bilel salem • Edited

First, I updated the code of the article because in Typescript the Document is a built-in interface representing the HTML Document Object Model (DOM) interface .

Second, yes you can add newDocument to the abstract class and this will facilitates our code, Thank you for the information .

Third, Regarding your concern about memory leaks and object access:

Object Lifetime: Assigning a new object to creator does not remove the previous instance. It only changes the reference in the creator variable. The previous instance is still accessible through any other references or will be garbage collected if no references exist.

Returning the Document: In your example, newDocument returns the created document. This ensures that the client code can maintain a reference to the created document, preventing memory leaks and allowing continued access.