Tuesday, January 10, 2012

Fluent interface in java


Simple and robust.

Task

I need to have several sets of methods of class, that can be invoked in special order using fluent interface. For example I need to have always first init(int a) method in a chain. In a second chain I need to have add(int a) and reset() methods. For the third chain I’d like to have dec(int a) and getValue() methods. getValue() method will return a result.

Solution

It’s good idea to use inner classes.
package org.sbelei;

public class FluentInterfaceSample {
     
      private SecondChain chain2;
      private ThirdChain chain3;
     
      private int value;

      {
            chain2 = new SecondChain();
            chain3 = new ThirdChain();
      }
     
      public static FluentInterfaceSample create(){
            return new FluentInterfaceSample();
      }
     
      public SecondChain init(int start){
            value = start;
            return chain2;
      }
     
      class SecondChain {
            public ThirdChain add(int a){
                  value += a;
                  return chain3;
            }
           
            public ThirdChain reset(){
                  value = 0;
                  return chain3;
            }
      }
     
      class ThirdChain {
            public ThirdChain dec(int b){
                  value -=b;
                  return chain3;
            }
           
            public int getValue(){
                  return value;
            }
      }
     
      public static void main(String[] args){
            int b = create().init(31).add(12).dec(10).getValue();
            System.out.println(b);
      }
}

No comments:

Post a Comment