The factory design pattern is a creational pattern. It assists us with creating new objects. Instead of using the new operator in order to create a new object we call the factory method and pass over arguments it uses to create the exact object we need.

The following code is a small sample for implementing the factory design pattern in JavaScript. The following code sample shows how we can create new objects without using the new operators by and calling a factory function that does the work and returns us a reference for a new object instantiated in according with the arguments we passed over.

<!DOCTYPE html>
<html>
<head>
    <title>factory design pattern sample</title>
    <script type="text/javascript">

        function Clerk( options ) {
            this.hourRate = options.hourRate || 20;
            this.firstName = options.firstName || "no first name";
            this.lastName = options.lastName || "no last name";
            this.id = options.id || "-9999999999";
        }

        function Manager( options) {
            this.hourRate = options.hourRate || 200;
            this.firstName = options.firstName || "no first name";
            this.lastName = options.lastName || "no last name";
            this.id = options.id || "-9999999999";
            this.yearBonus = options.yearBonus || "200000";
        }

        function Teacher( options) {
            this.hourRate = options.hourRate || 100;
            this.firstName = options.firstName || "no first name";
            this.lastName = options.lastName || "no last name";
            this.id = options.id || "-9999999999";
            this.subject = options.subject || "history";
        }

        var EmployeesFactory = function() {};

        EmployeesFactory.prototype.createEmployee = function (options) {
            if(options.employeeType == "Clerk")
                employeeConstructor = Clerk;
            else if(options.employeeType == "Manager")
                employeeConstructor = Manager;
            else if(options.employeeType == "Teacher")
                employeeConstructor = Teacher;
            return new employeeConstructor(options);
        }

        var factory = new EmployeesFactory();
        var person = factory.createEmployee( {
            employeeType: "Manager",
            firstName: "Haim",
            lastName: "Michael",
            id: 234234234 } );

        document.write(person instanceof Manager);
    </script>
</head>
<body>
</body>
</html>

The following video clip overviews the code sample, shows its execution and explains it in detail.

You can find more video clips, code samples and slides for learning about the design patterns we can implement in JavaScript using the free training material I publish at http://abelski.lifemichael.com.

Leave a Reply

Your email address will not be published. Required fields are marked *