javascriptdesign-patternsfactoryrevealing-module-pattern

Revealing pattern usecase


I'm reading a book called "Learning javascript design patterns" by Addy Osmani. This book is great.

There's an example of using the revealing design pattern:

var myRevealingModule = (function () {

    var privateVar = "Ben Cherry",
        publicVar = "Hey there!";

    function privateFunction() {
        console.log( "Name:" + privateVar );
    }

    function publicSetName( strName ) {
        privateVar = strName;
    }

    function publicGetName() {
        privateFunction();
    }


    // Reveal public pointers to
    // private functions and properties

    return {
        setName: publicSetName,
        greeting: publicVar,
        getName: publicGetName
    };

})();

myRevealingModule.setName( "Paul Kinlan" );

Now, of course I understand how it works, but my question simpler- what is the use case for using this in a regular, classic node webapp?

let's say I have a car module, that I wish to create in some procedure I have. I can't see how can I use the pattern in this case. How can I pass arguments to make new Car(args)?

Should I use this pattern for singletons? to create factories?


Solution

  • This pattern is used to encapsulate some private state while exposing ("revealing") a public interface.

    There can be many use cases for this pattern but in it's core it shows how to separate the implementation (the private variables) from the API (the exposed functions) which is not trivial to achieve in javascript.

    It's a good idea to use this whenever you have a module which has a state.

    To provide arguments, just expose an API function that accepts arguments, e.g.

    return {
        createCar: function(model, mileage) { ... }
    }