Factory Method Design Pattern in Javascript

September 19, 2017

This is the ShirtFactory constructor used to create LongSleeveShirt and ShortSleeveShirt objects


let ShirtFactory=(function(){

    function ShirtFactory(){

    }

    ShirtFactory.prototype.createShirt=function(stype){
        if(stype=="Long Sleeve"){
            return new LongSleeveShirt()
        }else if(stype=="Short Sleeve"){
            return new ShortSleeveShirt()
        }

    }
    return ShirtFactory
})()
let LongSleeveShirt=(function(){
    function LongSleeveShirt(){

    }
    LongSleeveShirt.prototype.make=function(){
        console.log('Long Sleeve Shirt Produced')
    }
    return LongSleeveShirt
})()
let ShortSleeveShirt=(function(){
    function ShortSleeveShirt(){

    }
    ShortSleeveShirt.prototype.make=function(){
        console.log('Short Sleeve Shirt Produced')
    }
    return ShortSleeveShirt
})()

I am using this client code to create shirt object and call the make() of each object

// client program

let sf= new ShirtFactory()
let shirt=sf.createShirt("Long Sleeve")
shirt.make()

shirt=sf.createShirt("Short Sleeve")
shirt.make()

First I am creating the ShirtFactory object sf and then call the createShirt() by passing argument to receive the shirt object. And finally call the make() to produce the shirts