本文介绍了策略模式或函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,当我有一个算法可以接受不同的行为在运行时我宁愿使用函数指针。

In C++ when I have algorithm which could accept different behaviour in runtime I rather use function pointer.

例如,绘制图表的程序有一个绘制线的算法,可以接受任何函数来专门处理此线的形状。

For example, a program for drawing charts has one algorithm to draw line which can accept any function to specialize shape of this line.

在Java中没有函数指针,我不得不使用策略模式或反射(或另一种模式)。

In Java there are no function pointers and I am obliged to use either the strategy pattern or reflection (or another pattern).

如何启用在我的程序中在运行时选择的特殊行为?
策略模式是函数指针?

How to to enable special behavior to be selected at runtime in my programme?Strategy pattern either function pointer?

推荐答案

在Java函数指针使用函数实现。使用一个函数创建一个接口,并传递它的实例,而不是函数指针。让我们在C ++中的代码看起来像:

In Java function pointers are implemented using functors. Create an interface with one function and pass instances of it instead of function pointers. Let's your code in C++ looked like:

void func(void (*f)(int par));

在Java中,这将是:

In Java this would look like:

public interface F {
  public void f(int par);
}

void func(F f);

查看Guava的类。这也不是一个坏的方法为C ++以及。它更可读,并允许用户传入状态而不是静态函数的对象。

Take a look at Guava's Function class. This is also not a bad approach for C++ as well. It is more readable and allows user to pass in objects with state as opposed to static functions.

这篇关于策略模式或函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 00:16