揭示模式用例

时间:2017-04-18 06:05:07

标签: javascript design-patterns factory revealing-module-pattern

我正在读一本名为"学习javascript设计模式的书#34;作者:Addy Osmani。这本书很棒。

有一个使用揭示设计模式的例子:

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.RECORD_AUDIO)) {

        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

         ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);

    }
}

现在,我当然理解它是如何工作的,但我的问题更简单 - 在常规的经典节点webapp中使用它的用例是什么?

让我们说我有一个汽车模块,我希望在某些程序中创建。在这种情况下,我无法看到如何使用该模式。如何传递参数以生成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" );

我应该将此模式用于单身人士吗?创建工厂?

3 个答案:

答案 0 :(得分:1)

此模式用于封装一些私有状态,同时公开(“揭示”)公共接口。

这种模式可以有很多用例,但在它的核心部分,它展示了如何将实现(私有变量)与API(暴露的函数)分开,这在javascript中实现并非易事。

每当有一个具有状态的模块时,最好使用它。

要提供参数,只需公开一个接受参数的API函数,例如

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

答案 1 :(得分:0)

JavaScript是一种奇怪的语言,如果你不遵循最佳实践并且你不熟悉ECMA标准,有时会做一些奇怪的事情。 JavaScript语法中有许多奇怪的东西,其中一个是自执行(自动调用)函数......

您可以在此处阅读更多详细信息

 http://blog.mgechev.com/2012/08/29/self-invoking-functions-in-javascript-or-immediately-invoked-function-expression/

您可以传递这样的参数:

https://jsfiddle.net/6bhn80oz/

答案 2 :(得分:0)

我在创建服务时经常在角度1中使用它。对我来说,更容易知道我可以在服务中访问哪些方法和/或变量,并将其他所有内容保留在return {}私有之外。

angular.module('myModule')
.factory('someService', function () {
    function myFunction(){
    }
    return{
        getSomething:myFunction
    }
});
相关问题