View Javadoc

1   /*
2    * Copyright 2004-2005 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * the License at
7    * 
8    * http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
15   */
16  package net.sf.composite.specialize.specializers;
17  
18  import java.util.Collections;
19  import java.util.HashMap;
20  import java.util.Map;
21  
22  import net.sf.composite.specialize.Specializer;
23  import net.sf.composite.util.ObjectPair;
24  
25  /***
26   * Caches specialized versions of a composite so that they do not have to be
27   * reconstructed for each request for a specialized version of the composite.
28   * 
29   * @author Matt Sgarlata
30   * @since Mar 11, 2005
31   */
32  public class CachingSpecializerProxy extends BaseSpecializer {
33  	
34  	private Specializer specializer;
35  	private Map cache = Collections.synchronizedMap(new HashMap());
36  	
37  	public CachingSpecializerProxy() {
38  		super();
39  	}
40  	
41  	public CachingSpecializerProxy(Specializer specializer) {
42  		super();
43  		this.specializer = specializer;
44  	}
45  	
46  	protected boolean isSpecializableImpl(Object composite,
47  		Class specializedType) throws Exception {
48  		return specializer.isSpecializable(composite, specializedType);
49  	}
50  
51  	protected Object specializeImpl(Object composite, Class specializedType) throws Exception {
52  		
53  		ObjectPair pair = new ObjectPair(composite, specializedType);
54  
55  		Object result = cache.get(pair);
56  		if (result == null) {
57  			result = getSpecializer().specialize(composite, specializedType);
58  			cache.put(pair, result);
59  		}
60  		return result;
61  	}
62  	
63  	public Specializer getSpecializer() {
64  		return specializer;
65  	}
66  	public void setSpecializer(Specializer specializer) {
67  		this.specializer = specializer;
68  	}
69  }