闭包:为什么它们如此有用? [英] Closures: why are they so useful?

查看:23
本文介绍了闭包:为什么它们如此有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 OO 开发人员,我可能很难看到它的价值.他们提供了什么附加价值?它们适合面向对象的世界吗?

As an OO developer, maybe I have difficulty seeing its value. What added value do they give? Do they fit in an OO world?

推荐答案

闭包不会给你任何额外的力量.

Closures don't give you any extra power.

有了它们你可以实现的任何事情,没有它们也能实现.

Anything you can achieve with them you can achieve without them.

但是它们对于使代码更清晰易读非常有用.众所周知,干净可读的短代码是一种更易于调试且包含更少错误的代码.

But they are very usable for making code more clear and readable. And as we all know clean readable short code is a code that is easier to debug and contains fewer bugs.

让我给您简短的 Java 示例,说明可能的用法:

Let me give you short Java example of possible usage:

    button.addActionListener(new ActionListener() {
        @Override public void actionPerformed(ActionEvent e) {
            System.out.println("Pressed");
        }
    });

将被替换(如果 Java 有闭包):

Would be replaced (if Java had closures) with:

button.addActionListener( { System.out.println("Pressed"); } );

这篇关于闭包:为什么它们如此有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆