Repository: iluwatar/java-design-patterns
Issue: Pattern : trampoline. Is it needed?
Labels: epic: pattern

Hi!
I have not found a pattern Trampoline in the list.
I want to discuss adding this pattern to list.

Will be it right?
I can do it if it is possible.

Issue comments:
Can you please provide links to the pattern?
Shure.
Wiki - https://en.wikipedia.org/wiki/Trampoline_(computing) (high-level programming)
good example - https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076
stackoverflow - https://stackoverflow.com/questions/189725/what-is-a-trampoline-function

2017-12-11 21:42 GMT+03:00 Ilkka Seppälä <notifications@github.com<mailto:notifications@github.com>>:

Can you please provide links to the pattern?

—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub<https://github.com/iluwatar/java-design-patterns/issues/677#issuecomment-350817317>, or mute the thread<https://github.com/notifications/unsubscribe-auth/Acc9YOi8BH4szX45S1GawlN7Dx8GIWBQks5s_XeqgaJpZM4Q9F1t>.


The links look good to me. Who would like to implement?
I can do it if you don't mind.
I am going to do it in 1-2 weeks.
Ok @besok 
ok.

Pull request review comments:
Would it be possible to explain the pattern shortly in `Explanation` section? See https://github.com/iluwatar/java-design-patterns/wiki/02.-Pattern-template and some other patterns like http://java-design-patterns.com/patterns/decorator/ for examples.
Use `Tutorials` section for examples. Pattern descriptions can be in `Credits`.
Using Lombok should be project level decision. We haven't used it elsewhere so please do not take it into use in one pattern.
Please refer to methods properly in Javadoc e.g. {@link package.class#member label}. What is cyclops-react?
Please prefer \<p\> tag in Javadoc. See other patterns for examples. Please describe what the example does and how it implements the pattern.
Please use descriptive test method name? What does it test?
Done. Changed to testTrampolineWithFactorialFunction 
done
cyclops-react is a library for additions java8 streams.
done.
done
i added section,
changed it.

Patch that resolved the issue:
diff --git a/pom.xml b/pom.xml
index 66c5fa850c83..7e669d39669c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -147,13 +147,13 @@
         <module>event-sourcing</module>
         <module>data-transfer-object</module>
         <module>throttling</module>
-
         <module>unit-of-work</module>
         <module>partial-response</module>
         <module>eip-wire-tap</module>
         <module>eip-splitter</module>
         <module>eip-aggregator</module>
         <module>retry</module>
+		<module>trampoline</module>
     </modules>
 
     <repositories>
diff --git a/trampoline/.gitignore b/trampoline/.gitignore
new file mode 100644
index 000000000000..431845ed0592
--- /dev/null
+++ b/trampoline/.gitignore
@@ -0,0 +1,2 @@
+/target/
+.idea/
diff --git a/trampoline/README.md b/trampoline/README.md
new file mode 100644
index 000000000000..cae343a61df9
--- /dev/null
+++ b/trampoline/README.md
@@ -0,0 +1,45 @@
+---
+layout: pattern
+title: Trampoline
+folder: trampoline
+permalink: /patterns/trampoline/
+categories: Behavior
+tags:
+ - Java
+ - Difficulty-Intermediate
+ - Performance
+ - Recursion
+---
+
+## Intent
+Trampoline pattern is used for implementing algorithms recursively in Java without blowing the stack 
+and to interleave the execution of functions without hard coding them together
+It is possible by representing a computation in one of 2 states : done | more 
+(completed with result, or a reference to the reminder of the computation, 
+something like the way a java.util.Supplier does).
+
+
+## Explanation
+Trampoline pattern allows to define recursive algorithms by iterative loop.
+
+
+## Applicability
+Use the Trampoline pattern when
+
+* For implementing tail recursive function. This pattern allows to switch on a stackless operation.
+* For interleaving the execution of two or more functions on the same thread.
+
+## Known uses(real world examples)
+* Trampoline refers to using reflection to avoid using inner classes, for example in event listeners. 
+The time overhead of a reflection call is traded for the space overhead of an inner class. 
+Trampolines in Java usually involve the creation of a GenericListener to pass events to an outer class.
+
+
+## Tutorials 
+* [Trampolining: a practical guide for awesome Java Developers](https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076)
+* [Trampoline in java ](http://mindprod.com/jgloss/trampoline.html)
+
+## Credits
+* [library 'cyclops-react' uses the pattern](https://github.com/aol/cyclops-react)
+
+
diff --git a/trampoline/pom.xml b/trampoline/pom.xml
new file mode 100644
index 000000000000..71de3f8f2684
--- /dev/null
+++ b/trampoline/pom.xml
@@ -0,0 +1,77 @@
+<?xml version="1.0"?>
+<!--
+
+    The MIT License
+    Copyright (c) 2014-2016 Ilkka Seppälä
+
+    Permission is hereby granted, free of charge, to any person obtaining a copy
+    of this software and associated documentation files (the "Software"), to deal
+    in the Software without restriction, including without limitation the rights
+    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+    copies of the Software, and to permit persons to whom the Software is
+    furnished to do so, subject to the following conditions:
+
+    The above copyright notice and this permission notice shall be included in
+    all copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+    THE SOFTWARE.
+
+-->
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
+         xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>com.iluwatar</groupId>
+        <artifactId>java-design-patterns</artifactId>
+        <version>1.19.0-SNAPSHOT</version>
+
+    </parent>
+    <artifactId>trampoline</artifactId>
+    <dependencies>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>4.12</version>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.junit.jupiter</groupId>
+            <artifactId>junit-jupiter-api</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.junit.jupiter</groupId>
+            <artifactId>junit-jupiter-engine</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <version>1.16.18</version>
+        </dependency>
+
+
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <version>2.19</version>
+                <configuration>
+                    <skipTests>false</skipTests>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+</project>
diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java
new file mode 100644
index 000000000000..277ae9ffbad1
--- /dev/null
+++ b/trampoline/src/main/java/com/iluwatar/trampoline/Trampoline.java
@@ -0,0 +1,85 @@
+package com.iluwatar.trampoline;
+
+import java.util.stream.Stream;
+
+/**
+ * <p>Trampoline pattern allows to define recursive algorithms by iterative loop </p>
+ * <p>When get is called on the returned Trampoline, internally it will iterate calling ‘jump’
+ * on the returned Trampoline as long as the concrete instance returned is {@link #more(Trampoline)},
+ * stopping once the returned instance is {@link #done(Object)}.</p>
+ * <p>Essential we convert looping via recursion into iteration,
+ * the key enabling mechanism is the fact that {@link #more(Trampoline)} is a lazy operation.</p>
+ *
+ * @param <T> is  type for returning result.
+ */
+public interface Trampoline<T> {
+  T get();
+
+
+  /**
+   * @return next stage
+   */
+  default Trampoline<T> jump() {
+    return this;
+  }
+
+
+  default T result() {
+    return get();
+  }
+
+  /**
+   * @return true if complete
+   */
+  default boolean complete() {
+    return true;
+  }
+
+  /**
+   * Created a completed Trampoline
+   *
+   * @param result Completed result
+   * @return Completed Trampoline
+   */
+  static <T> Trampoline<T> done(final T result) {
+    return () -> result;
+  }
+
+
+  /**
+   * Create a Trampoline that has more work to do
+   *
+   * @param trampoline Next stage in Trampoline
+   * @return Trampoline with more work
+   */
+  static <T> Trampoline<T> more(final Trampoline<Trampoline<T>> trampoline) {
+    return new Trampoline<T>() {
+      @Override
+      public boolean complete() {
+        return false;
+      }
+
+      @Override
+      public Trampoline<T> jump() {
+        return trampoline.result();
+      }
+
+      @Override
+      public T get() {
+        return trampoline(this);
+      }
+
+      T trampoline(final Trampoline<T> trampoline) {
+
+        return Stream.iterate(trampoline, Trampoline::jump)
+            .filter(Trampoline::complete)
+            .findFirst()
+            .get()
+            .result();
+
+      }
+    };
+  }
+
+
+}
diff --git a/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java b/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java
new file mode 100644
index 000000000000..76e3ed3da080
--- /dev/null
+++ b/trampoline/src/main/java/com/iluwatar/trampoline/TrampolineApp.java
@@ -0,0 +1,58 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014-2016 Ilkka Seppälä
+ * <p>
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ * <p>
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ * <p>
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package com.iluwatar.trampoline;
+
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * <p>Trampoline pattern allows to define recursive algorithms by iterative loop </p>
+ * <p>it is possible to implement algorithms recursively in Java without blowing the stack
+ * and to interleave the execution of functions without hard coding them together or even using threads.</p>
+ */
+@Slf4j
+public class TrampolineApp {
+
+  /**
+   * Main program for showing pattern. It does loop with factorial function.
+   * */
+  public static void main(String[] args) {
+    log.info("start pattern");
+    Integer result = loop(10, 1).result();
+    log.info("result {}", result);
+
+  }
+
+  /**
+   * Manager for pattern. Define it with a factorial function.
+   */
+  public static Trampoline<Integer> loop(int times, int prod) {
+    if (times == 0) {
+      return Trampoline.done(prod);
+    } else {
+      return Trampoline.more(() -> loop(times - 1, prod * times));
+    }
+  }
+
+}


Test patch:
diff --git a/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java b/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java
new file mode 100644
index 000000000000..553e583e12e9
--- /dev/null
+++ b/trampoline/src/test/java/com/iluwatar/trampoline/TrampolineAppTest.java
@@ -0,0 +1,22 @@
+package com.iluwatar.trampoline;
+
+import org.junit.Test;
+
+import java.io.IOException;
+
+import static org.junit.Assert.*;
+
+
+/**
+ * Test for trampoline pattern.
+ * */
+public class TrampolineAppTest {
+
+
+  @Test
+  public void testTrampolineWithFactorialFunction() throws IOException {
+    int result = TrampolineApp.loop(10, 1).result();
+    assertEquals("Be equal", 3628800, result);
+  }
+
+}
\ No newline at end of file