0

I've been reading a Concepts of Programming Languages by Robert W. Sebesta and in chapter 9 there is a brief section on passing a SubProgram to a function as a parameter. The section on this is extremely brief, about 1.5 pages, and the only explanation to its application is:

When a subprogram must sample some mathematical function. Such as a Subprogram that does numerical integration by estimating the area under a graph of a function by sampling the function at a number of different points. Such a Subprogram should be usable everywhere.

This is completely off from anything I have ever learned. If I were to approach this problem in my own way I would create a function object and create a function that accomplishes the above and accepts function objects.

I have no clue why this is a design issue for languages because I have no idea where I would ever use this. A quick search hasn't made this any clearer for me.

Apparently you can accomplish this in C and C++ by utilizing pointers. Languages that allow nested Subprograms such as JavaScript allow you do do this in 3 separate ways:

function sub1() {
    var x;
    function sub2() {
        alert( x ); //Creates a dialog box with the value of x
        };
    function sub3() {
        var x;
        x = 3;
        sub4( sub2 ); //*shallow binding* the environment of the                                 
                      //call statement that enacts the passed 
                      //subprogram
        };
    function sub4( subx ) {
        var x;
        x = 4;
        subx();
        };
    x=1;
    sub3();
    };

I'd appreciate any insight offered.

4

1 回答 1

1

由于各种原因,能够通过“方法”非常有用。其中:

  • 执行复杂操作的代码可能希望提供一种通知用户其进度或允许用户取消它的方法。拥有复杂操作的代码必须自己执行这些操作,这既会增加复杂性,也会导致丑陋,如果它是从使用不同样式的进度条或“取消”按钮的代码中调用的。相比之下,让调用者提供 UpdateStatusAndCheckCancel() 方法意味着调用者可以提供一个方法,该方法将更新调用者想要使用的任何样式的进度条和取消方法。

  • 能够在表中存储方法可以大大简化需要将对象导出到文件并稍后再次导入它们的代码。而不是需要让代码说

    if (ObjectType == "Square")
      AddObject(new Square(ObjectParams));
    else if (ObjectType == "Circle")
      AddObject(new Circle(ObjectParams));` 
    etc. for every kind of object
    

    代码可以说类似

    if (ObjectCreators.TryGetValue(ObjectType, out factory))
      AddObject(factory(ObjectParams));
    

    处理添加了创建方法的各种对象ObjectCreators

  • 有时希望能够处理未来某个未知时间可能发生的事件;知道这些事件何时发生的代码作者可能不知道那时应该发生什么事情。允许希望动作发生的人为代码提供一个方法,该方法将知道它何时发生,这样代码就可以在正确的时间执行动作,而不必知道它应该做什么。

第一种情况代表回调的一种特殊情况,其中给定方法的函数预计仅在返回之前使用它。第二种情况是有时被称为“工厂模式”或“依赖注入”的示例[尽管这些术语在某些更广泛的上下文中也很有用]。第三种情况通常使用框架称为事件的构造来处理,或者使用“观察者”模式[观察者要求可观察对象在发生某些事情时通知它]。

于 2013-10-02T16:56:04.373 回答