| 1 | package de.uka.ipd.sdq.sensorframework.adapter; |
| 2 | |
| 3 | import java.util.ArrayList; |
| 4 | import java.util.HashMap; |
| 5 | import java.util.List; |
| 6 | |
| 7 | /** |
| 8 | * This registry can store adapter factories |
| 9 | * (cf. interface {@link IAdapterFactory}), |
| 10 | * but cannot remove them. It can be queried, but not reset. |
| 11 | * @author Steffen Becker |
| 12 | * |
| 13 | */ |
| 14 | public class AdapterRegistry { |
| 15 | |
| 16 | private static AdapterRegistry singletonInstance = new AdapterRegistry();//why not final? |
| 17 | |
| 18 | private static HashMap<String,IAdapterFactory> factories = new HashMap<String,IAdapterFactory>(); |
| 19 | |
| 20 | public static AdapterRegistry singleton() { |
| 21 | return singletonInstance; |
| 22 | } |
| 23 | |
| 24 | private AdapterRegistry() {} |
| 25 | |
| 26 | public void addAdapterFactory(IAdapterFactory adapterFactory){ |
| 27 | factories.put(adapterFactory.getAdapterFactoryID(),adapterFactory); |
| 28 | } |
| 29 | |
| 30 | public boolean canAdapt(Object adaptee, Class<?> targetClass) { |
| 31 | //inefficient: iterate over factories and if one is found, abort immediately, returning true |
| 32 | return getAllAvailableFactories(adaptee, targetClass).size() > 0; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Returns the first adapter suitable for passed parameters |
| 37 | * @param objToAdapt |
| 38 | * @param class1 |
| 39 | * @return |
| 40 | */ |
| 41 | public IAdapter getAdapter(Object objToAdapt, Class<?> class1) { |
| 42 | return getAllAvailableFactories(objToAdapt, class1).get(0).getAdapter(objToAdapt); |
| 43 | } |
| 44 | |
| 45 | public List<IAdapterFactory> getAllAvailableFactories(Class<?> targetClass) { |
| 46 | ArrayList<IAdapterFactory> result = new ArrayList<IAdapterFactory>(); |
| 47 | for(IAdapterFactory factory : factories.values()){ |
| 48 | if (factory.createsAdaptersFor(targetClass)) |
| 49 | { |
| 50 | result.add(factory); |
| 51 | } |
| 52 | } |
| 53 | return result; |
| 54 | } |
| 55 | |
| 56 | public List<IAdapterFactory> getAllAvailableFactories(Object adaptee, Class<?> targetClass) { |
| 57 | ArrayList<IAdapterFactory> result = new ArrayList<IAdapterFactory>(); |
| 58 | for(IAdapterFactory factory : factories.values()){ |
| 59 | if (factory.canAdapt(adaptee,targetClass)) |
| 60 | { |
| 61 | result.add(factory); |
| 62 | } |
| 63 | } |
| 64 | return result; |
| 65 | } |
| 66 | |
| 67 | public IAdapterFactory getFactoryByID(String factoryID){ |
| 68 | return factories.get(factoryID); |
| 69 | } |
| 70 | |
| 71 | } |