Java中钩子和抽象方法的区别

发布于 2024-10-14 05:38:30 字数 251 浏览 3 评论 0原文

这是我大学学习材料中引用的一个问题。

这对我来说完全没有意义。

对我来说,钩子是程序中的指定点(主要是顺序的,但不仅仅是),您可以在其中指定要执行的自己的方法或回调。

例如,一个应用程序有一个“关闭前打开钩子”,我可以在那里注册我的回调方法,在关闭之前将用户数据保存到磁盘。

抽象方法是自我解释的。

对我来说这是完全不同的事情吗?或者这两件事是否有我不知道的第二个含义?我快速搜索了一下,但没有找到任何东西。

This is a quoted question from the study materials from my university.

It makes totally no sense to me.

For me hooks are specified points in (mostly sequential but not only) programs, where you can specify your own methods or callbacks to be executed.

For example an application has an "on before shutdown hook", i can register my callback method there that saves the user data to disk before shutdown.

Abstract methods are self explaining.

To me this is something completely different? or does either of those things have a 2nd meaning I don't know of? I did a quick search but didn't find anything.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

木森分化 2024-10-21 05:38:30

我真的不认为这两件事非常相似。它们可能相关的一种方式可以在下面演示:

public abstract class AbstractActionDoer() {
    public void doAction(Action act) {
        beforeAction();
        act.do();
        afterAction();
    }
    protected abstract void beforeAction();
    protected abstract void afterAtion();
}

public class DefaultActionDoer() extends AbstractActionDoer {
    public void doAction(Action act) {
        beforeAction();
        act.do();
        afterAction();
    }
    // default empty implementation
    protected void beforeAction() { }
    protected void afterAtion() { }
}

在此示例中,您可以在 DefaultActionDoer 中重写挂钩以更改功能,但它们不是必需的。这类似于抽象方法,因为抽象方法需要被重写来定义功能。

I really don't see these two things as being very similar. One way they may be related can be demonstrated in the following:

public abstract class AbstractActionDoer() {
    public void doAction(Action act) {
        beforeAction();
        act.do();
        afterAction();
    }
    protected abstract void beforeAction();
    protected abstract void afterAtion();
}

public class DefaultActionDoer() extends AbstractActionDoer {
    public void doAction(Action act) {
        beforeAction();
        act.do();
        afterAction();
    }
    // default empty implementation
    protected void beforeAction() { }
    protected void afterAtion() { }
}

In this example, you have hooks that can be overridden in DefaultActionDoer to change the functionality, but they are not required. This is similar to an abstract method because the abstract methods need to be overriden to define the functionality.

贩梦商人 2024-10-21 05:38:30

抽象方法是实现“钩子”的一种方式。钩子可以通过回调、观察者模式、插件来实现...任何您想要指定外部代码在应用程序中的重要点(称为钩子)运行的方式。

Abstract methods are one way of implementing "hooks". Hooks can be implemented through callbacks, observer pattern, plugins... Any way you'd like to specify that some code from the outside gets to run at important points, called hooks, in your app.

永不分离 2024-10-21 05:38:30

对我来说这是完全不同的事情?

它们都是将代码推迟到客户端类(类的用户)的方法:

1) 定义抽象方法

  • 类中的其他方法调用抽象方法。
  • 该类的客户端必须扩展该类以提供缺少的代码。

2)定义一个钩子

  • 该类有一个关联的回调接口(它只是一堆抽象方法)。
  • 类的方法调用回调方法。
  • 该类的客户端必须实现关联的回调并注册它以提供缺少的代码。

当然,您选择一种方法而不是另一种方法的原因有多种。例如,挂钩方法允许您注册多个回调。但抽象方法提供了对类的更直接的访问(受保护的方法和 ivars)。


这可能是太多信息,但在 android 编程中您会看到两者:

您可以提供一个 CursorAdapter 将数据源关联到 UI 小部件。

http://developer.android.com/reference/android/widget/CursorAdapter.html

这个类是抽象的,有两个方法 newViewbindView 来将数据实际绑定到 UI 小部件。类必须子类化才能使用此类。


但是,CursorAdapter 的子类是 SimpleCursorAdapter

http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html

这个类实现了 newViewbindView 并选择提供客户端可以实现并向 SimpleCursorAdapter 实例注册的 ViewBinder 接口。 ViewBinder 实例必须提供 setViewValue 方法,将特定的数据绑定到特定的 UI 小部件。

与 SimpleCursorAdapter 的一个主要区别是提供 ViewBinder 是可选的,这是钩子方法的优点之一。

To me this is something completely different?

They are both methods to defer code to a client class (a user of your class):

1) Define an abstract method

  • The other methods in the class call the abstract methods.
  • Clients of the class must extend the class to provide the missing code.

2) Define a hook

  • The class has an associated callback interface (which is simply a bunch of abstract methods).
  • The methods of the class call the callback methods.
  • Clients of the class must implement the associated callback and register it to provide the missing code.

There are of course a variety of reasons why you'd use one approach over the other. For example, a hook approach allows you to register multiple callbacks. But the abstract approach provides more direct access to the class (protected methods and ivars).


This is probably too much information, but in android programming you see both:

You can provide a CursorAdapter to associate a data source to a UI widget.

http://developer.android.com/reference/android/widget/CursorAdapter.html

This class is abstract and has two methods newView and bindView that do the actual binding of the data to the UI widgets. Classes must subclass to use this class.


However, a subclass of CursorAdapter is SimpleCursorAdapter

http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html

This class implements newView and bindView and opts to provide a ViewBinder interface that clients may implement and register with the SimpleCursorAdapter instance. The ViewBinder instance must provide the setViewValue method that binds a specific piece of data to a specific UI widget.

One key difference with SimpleCursorAdapter is that providing a ViewBinder is optional, which is one of the advantages of the hook approach.

青柠芒果 2024-10-21 05:38:30

就我个人而言,在询问 StackOverflow 社区之前,我会去找教授并要求澄清。

...但是,话虽如此,我相信(如果您对钩子的描述是正确的)任何类都可以为钩子注册回调方法,而抽象方法则强制子类 a 为给定方法实现自己的算法。

Personally, I would go to the professor and ask for clarification before asking the StackOverflow community.

...but, that being said, I believe (if your description of a hook is correct) that any class can register a callback method for a hook whereas an abstract method forces a child class a to implement its own algorithm for the given method.

厌倦 2024-10-21 05:38:30

概念与实现细节肯定存在一些混淆。

基本上你的理解是正确的。

引用OP的声明,是什么是:

挂钩是指定的点,开发人员可以在其中指定要执行的方法或回调。

Javascript 语言可能是最(臭名昭著)的允许一切都被挂钩的语言。 (顺便说一句:Google 有一个安全漏洞,涉及 Javascript 数组构造函数被挂钩)

实现抽象方法/回调接口是在 Java 代码中如何实现回调的机制。

There was definitely some conflation of concepts with implementation details.

Basically your understanding is correct.

To quote back the OP's statement, the what is :

Hooks are specified points, where the developer can specify methods or callbacks to be executed.

Javascript language is probably the most (notorious) language for allowing everything to be hooked. (As a side note: Google had a security hole that involved the Javascript Array constructor being hooked)

Implementing an abstract method/callback interface is the mechanism how the callback is realized in java code.

网名女生简单气质 2024-10-21 05:38:30

hook 是一个古老的术语,可能可以追溯到 20 世纪 80 年代之前。从你的问题中不清楚“在Java中”是否适用于Hooks和抽象方法,但如果我是一名教授(!),我认为了解Hooks的历史(在Java之前)很重要。

有一个维基百科页面详细介绍了Hooking。就我个人而言,当我想到钩子时,我想到的是允许运行时定制的机制。

以下是在 http://www.tldp.org 中找到的一些定义/LDP/Linux-Dictionary/html/h.html

挂钩

软件或硬件产品中包含的功能,使爱好者和程序员能够添加自己的自定义功能。来自 QUECID

钩子

n。为了简化用户以后的添加或更改而包含的软件或硬件功能。例如,一个打印数字的简单程序可能总是以 10 为基数打印它们,但更灵活的版本将让变量确定要使用的基数;将变量设置为 5 将使程序以 5 为基数打印数字。该变量是一个简单的钩子。更灵活的程序可能会检查变量并将 16 或更小的值视为要使用的基数,但将任何其他数字视为用户提供的用于打印数字的例程的地址。这是一个毛茸茸但有力的钩子;然后,我们可以编写一个例程,将数字打印为罗马数字或希伯来字符,并通过钩子将其插入程序中。通常,一个好的程序和一个出色的程序之间的区别在于,后者在明智选择的地方有有用的钩子。两者都可以同样出色地完成最初的工作,但带有钩子的那个对于未来功能的扩展更加灵活(例如,EMACS 都是钩子)。术语“用户退出”是同义词,但更加正式且不那么黑客化。来自行话词典

挂钩

将代码插入系统调用以更改它的技术。典型的钩子的工作原理是用自己的函数指针替换调用的函数指针,然后一旦完成处理,它将调用原始函数指针。来自 Hacking-Lexicon


至于 Java 中的抽象方法Bert F 的回答。我要强调的是,与钩子的一般概念(允许定制)不同,抽象方法需要规范,这意味着没有默认定义。

A hook is an old term, probably dating to before the 1980s. It's not clear from your question if "in Java" applies to both Hooks and Abstract Methods, but if I were a professor (!), I would think it's important to understand the history of hooks (before Java).

There's a Wikipedia page that goes into great detail about Hooking. Personally, when I think of hook, I think of mechanisms that allow run-time customization.

Here are a few definitions found at http://www.tldp.org/LDP/Linux-Dictionary/html/h.html

Hook

A feature included in a software or hardware product to enable hobbyists and programmers to add their own custom features. From QUECID

hook

n. A software or hardware feature included in order to simplify later additions or changes by a user. For example, a simple program that prints numbers might always print them in base 10, but a more flexible version would let a variable determine what base to use; setting the variable to 5 would make the program print numbers in base 5. The variable is a simple hook. An even more flexible program might examine the variable and treat a value of 16 or less as the base to use, but treat any other number as the address of a user-supplied routine for printing a number. This is a hairy but powerful hook; one can then write a routine to print numbers as Roman numerals, say, or as Hebrew characters, and plug it into the program through the hook. Often the difference between a good program and a superb one is that the latter has useful hooks in judiciously chosen places. Both may do the original job about equally well, but the one with the hooks is much more flexible for future expansion of capabilities (EMACS, for example, is all hooks). The term `user exit' is synonymous but much more formal and less hackish. From Jargon Dictionary

hook

The technique of inserting code into a system call in order to alter it. The typical hook works by replacing the function pointer to the call with its own, then once it is done doing its processing, it will then call the original function pointer. From Hacking-Lexicon


As for Abstract methods in Java, it was pretty well explained in Bert F's answer. I'll stress that unlike the general notion of hooks (which allows customization), abstract methods require specification, meaning there is no default definition.

江城子 2024-10-21 05:38:30

据我的理解:

抽象方法

  • 所需的
  • 步骤必须定制/实现

Hooks

  • 可选的
  • 抽象类可以提供默认的实现

示例

public abstract class AbstractClass() {
    public void final templateMethod() {
        operation1();
        operation2();
        operation3();
        operation4();
    }
    void final operation1() {/* do some stuff, cannot be changed */}
    void final operation2() {/* do some other stuff which cannot be overridden */}
    abstract void operation3(); // ConcreteClass has to implement it
    void operation4() {/* do nothing */} // This is effectively a hook
}

public class ConcreteClass() extends AbstractClass {
    @Override
    void operation3() {/* implementing mandatory step*/}

    @Override //optional, I don't have to implement/override this method
    void operation4() {/* I can choose if more detailed steps needs to be implemented */}
}

To my understanding:

Abstract Methods

  • required
  • steps that must be customized/implemented

Hooks

  • optional
  • abstract class may provide a default implementation

Example

public abstract class AbstractClass() {
    public void final templateMethod() {
        operation1();
        operation2();
        operation3();
        operation4();
    }
    void final operation1() {/* do some stuff, cannot be changed */}
    void final operation2() {/* do some other stuff which cannot be overridden */}
    abstract void operation3(); // ConcreteClass has to implement it
    void operation4() {/* do nothing */} // This is effectively a hook
}

public class ConcreteClass() extends AbstractClass {
    @Override
    void operation3() {/* implementing mandatory step*/}

    @Override //optional, I don't have to implement/override this method
    void operation4() {/* I can choose if more detailed steps needs to be implemented */}
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文