KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ant > internal > ui > dtd > util > Factory


1 /*******************************************************************************
2  * Copyright (c) 2002, 2005 Object Factory Inc.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * Object Factory Inc. - Initial implementation
10  *******************************************************************************/

11 package org.eclipse.ant.internal.ui.dtd.util;
12
13 import java.lang.ref.SoftReference JavaDoc;
14
15 /**
16  * Factory maintains a free list and, with FactoryObject,
17  * serves as a basis for factories of all types.
18  * Factory should only be subclassed in singleton classes;
19  * for static factories, it may be instantiated as
20  * a static object.
21  * @author Bob Foster
22  */

23 public class Factory {
24     
25     /**
26      * Return the first object on the free list
27      * or null if none.
28      */

29     public FactoryObject getFree() {
30         Head head = getHead();
31         FactoryObject obj = head.next;
32         if (obj != null) {
33             head.next = obj.next();
34             obj.next(null);
35         }
36         return obj;
37     }
38     
39     /**
40      * Add an object to the free list.
41      */

42     public void setFree(FactoryObject obj) {
43         Head head = getHead();
44         obj.next(head.next);
45         head.next = obj;
46     }
47     
48     private Head getHead() {
49         Head head = (Head) free.get();
50         if (head == null) {
51             // head is needed because you can't change
52
// the referent of a SoftReference.
53
// Without head, we would need to create
54
// a new SoftReference each time we remove
55
// a map from the list. With head, getting
56
// a free object only causes memory allocation
57
// when the list has been previously collected.
58
head = new Head();
59             free = new SoftReference JavaDoc(head);
60         }
61         return head;
62     }
63
64     private static class Head {
65         public FactoryObject next;
66     }
67     private SoftReference JavaDoc free = new SoftReference JavaDoc(new Head());
68 }
69
Popular Tags