What's the nearest substitute for a function pointer in Java?

前端 未结 22 1862
太阳男子
太阳男子 2020-11-22 15:32

I have a method that\'s about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that\'s going to change one li

22条回答
  •  青春惊慌失措
    2020-11-22 16:09

    @sblundy's answer is great, but anonymous inner classes have two small flaws, the primary being that they tend not to be reusable and the secondary is a bulky syntax.

    The nice thing is that his pattern expands into full classes without any change in the main class (the one performing the calculations).

    When you instantiate a new class you can pass parameters into that class which can act as constants in your equation--so if one of your inner classes look like this:

    f(x,y)=x*y
    

    but sometimes you need one that is:

    f(x,y)=x*y*2
    

    and maybe a third that is:

    f(x,y)=x*y/2
    

    rather than making two anonymous inner classes or adding a "passthrough" parameter, you can make a single ACTUAL class that you instantiate as:

    InnerFunc f=new InnerFunc(1.0);// for the first
    calculateUsing(f);
    f=new InnerFunc(2.0);// for the second
    calculateUsing(f);
    f=new InnerFunc(0.5);// for the third
    calculateUsing(f);
    

    It would simply store the constant in the class and use it in the method specified in the interface.

    In fact, if KNOW that your function won't be stored/reused, you could do this:

    InnerFunc f=new InnerFunc(1.0);// for the first
    calculateUsing(f);
    f.setConstant(2.0);
    calculateUsing(f);
    f.setConstant(0.5);
    calculateUsing(f);
    

    But immutable classes are safer--I can't come up with a justification to make a class like this mutable.

    I really only post this because I cringe whenever I hear anonymous inner class--I've seen a lot of redundant code that was "Required" because the first thing the programmer did was go anonymous when he should have used an actual class and never rethought his decision.

提交回复
热议问题