KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > prefuse > util > force > Spring


1 package prefuse.util.force;
2
3 import java.util.ArrayList JavaDoc;
4
5 /**
6  * Represents a spring in a force simulation.
7  *
8  * @author <a HREF="http://jheer.org">jeffrey heer</a>
9  */

10 public class Spring {
11     private static SpringFactory s_factory = new SpringFactory();
12     
13     /**
14      * Retrieve the SpringFactory instance, which serves as an object pool
15      * for Spring instances.
16      * @return the Spring Factory
17      */

18     public static SpringFactory getFactory() {
19         return s_factory;
20     }
21     
22     /**
23      * Create a new Spring instance
24      * @param fi1 the first ForceItem endpoint
25      * @param fi2 the second ForceItem endpoint
26      * @param k the spring tension co-efficient
27      * @param len the spring's resting length
28      */

29     public Spring(ForceItem fi1, ForceItem fi2, float k, float len) {
30         item1 = fi1;
31         item2 = fi2;
32         coeff = k;
33         length = len;
34     }
35     
36     /** The first ForceItem endpoint */
37     public ForceItem item1;
38     /** The second ForceItem endpoint */
39     public ForceItem item2;
40     /** The spring's resting length */
41     public float length;
42     /** The spring tension co-efficient */
43     public float coeff;
44     
45     /**
46      * The SpringFactory is responsible for generating Spring instances
47      * and maintaining an object pool of Springs to reduce garbage collection
48      * overheads while force simulations are running.
49      */

50     public static final class SpringFactory {
51         private int maxSprings = 10000;
52         private ArrayList JavaDoc springs = new ArrayList JavaDoc();
53         
54         /**
55          * Get a Spring instance and set it to the given parameters.
56          */

57         public Spring getSpring(ForceItem f1, ForceItem f2, float k, float length) {
58             if ( springs.size() > 0 ) {
59                 Spring s = (Spring)springs.remove(springs.size()-1);
60                 s.item1 = f1;
61                 s.item2 = f2;
62                 s.coeff = k;
63                 s.length = length;
64                 return s;
65             } else {
66                 return new Spring(f1,f2,k,length);
67             }
68         }
69         /**
70          * Reclaim a Spring into the object pool.
71          */

72         public void reclaim(Spring s) {
73             s.item1 = null;
74             s.item2 = null;
75             if ( springs.size() < maxSprings )
76                 springs.add(s);
77         }
78     } // end of inner class SpringFactory
79

80 } // end of class Spring
81
Popular Tags