What's a fluent interface?

前端 未结 4 1693
无人及你
无人及你 2020-12-15 07:29

I recently came across this expression - but reading up on Wikipedia did not clarify it much for me - I still don\'t get it:

  1. What\'s the point of it
  2. H
相关标签:
4条回答
  • 2020-12-15 07:38

    It benefits the coder by reducing the amount he has to type (and read).

    To use the C++ example on Wikipedia:

    Before:

    int main(int argc, char **argv) {
         GlutApp app(argc, argv);
         app.setDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_ALPHA|GLUT_DEPTH); // Set framebuffer params
         app.setWindowSize(500, 500); // Set window params
         app.setWindowPosition(200, 200);
         app.setTitle("My OpenGL/GLUT App");
         app.create();
    }
    

    After:

     int main(int argc, char **argv) {
         FluentGlutApp app(argc, argv)
             .withDoubleBuffer().withRGBA().withAlpha().withDepth()
             .at(200, 200).across(500, 500)
             .named("My OpenGL/GLUT App");
         app.create();
     }
    
    0 讨论(0)
  • 2020-12-15 07:43

    One big difference and advantage of the fluent interface is that you don't need an instance variable to change some properties when you want to create an object and use it as an argument:

    without:

    Object object;
    object.setcolor("red"); 
    object.setstyle("solid");
    object.setname("test");
    world.CreateNode(object);
    

    with fluent interface:

    world.CreateNode(Object()
                                               .setcolor("red")
                                               .setstyle("solid")
                                               .setname("test")
                                 );
    
    0 讨论(0)
  • 2020-12-15 07:45

    CallStream aka "Why the dot's ?" :)

    Nothing wrong with a bit of (very simple) JavaScript to describe new and important concepts. Perfectly doable in C++, too.cept

    Key concept: using Functional Programming idiom, describe the interface. Without using: message argument as a string, to be parsed, concept.

    I think it is mostly related to the "Facade" pattern, but yes, it is related to a "Builder pattern". And it seems it survived the "Monads" too.

    btw: All the advocates above have presented very good use-cases.

    0 讨论(0)
  • 2020-12-15 07:46

    There are different interpretations of the term "fluent interface". A common way to create one in C++ is method chaining, which is commonly used in for example the iostream library:

    Object.MethodA().MethodB();
    cout << "a = " << a;
    

    The Named Parameter Idiom is another nice example of a fluent interface:

    Window w = CreateWindow()
                   .Width(400)
                   .Height(300)
                   .OnTop();
    

    The benefits? Code that's better readable and more flexible, although that still depends on the implementation of course.

    0 讨论(0)
提交回复
热议问题