1 11 12 package org.eclipse.ui.internal.services; 13 14 import java.util.HashMap ; 15 import java.util.Iterator ; 16 import java.util.Map ; 17 18 import org.eclipse.swt.widgets.Shell; 19 import org.eclipse.ui.services.IDisposable; 20 import org.eclipse.ui.services.IServiceLocator; 21 22 26 public final class ServiceLocator implements IDisposable, INestable, 27 IServiceLocator { 28 29 34 private final IServiceLocator parent; 35 36 42 private Map services = null; 43 44 47 public ServiceLocator() { 48 this(null); 49 } 50 51 58 public ServiceLocator(final IServiceLocator parent) { 59 this.parent = parent; 60 } 61 62 public final void activate() { 63 if (services != null) { 64 final Iterator serviceItr = services.values().iterator(); 65 while (serviceItr.hasNext()) { 66 final Object service = serviceItr.next(); 67 if (service instanceof INestable) { 68 final INestable nestableService = (INestable) service; 69 nestableService.activate(); 70 } 71 } 72 } 73 } 74 75 public final void deactivate() { 76 if (services != null) { 77 final Iterator serviceItr = services.values().iterator(); 78 while (serviceItr.hasNext()) { 79 final Object service = serviceItr.next(); 80 if (service instanceof INestable) { 81 final INestable nestableService = (INestable) service; 82 nestableService.deactivate(); 83 } 84 } 85 } 86 } 87 88 public final void dispose() { 89 if (services != null) { 90 final Iterator serviceItr = services.values().iterator(); 91 while (serviceItr.hasNext()) { 92 final Object object = serviceItr.next(); 93 if (object instanceof IDisposable) { 94 final IDisposable service = (IDisposable) object; 95 service.dispose(); 96 } 97 } 98 services = null; 99 } 100 } 101 102 public final Object getService(final Class key) { 103 final Object service; 104 if (services != null) { 105 service = services.get(key); 106 } else { 107 service = null; 108 } 109 if ((service == null) && (parent != null)) { 110 return parent.getService(key); 111 } 112 113 return service; 114 } 115 116 public final boolean hasService(final Class key) { 117 if (services != null) { 118 if (services.containsKey(key)) { 119 return true; 120 } 121 } 122 123 return false; 124 } 125 126 138 public final void registerService(final Class api, final Object service) { 139 if (api == null) { 140 throw new NullPointerException ("The service key cannot be null"); } 142 143 if (!api.isInstance(service)) { 144 throw new IllegalArgumentException ( 145 "The service does not implement the given interface"); } 147 148 if (services == null) { 149 services = new HashMap (); 150 } 151 152 if (services.containsKey(api)) { 153 final Object currentService = services.remove(api); 154 if (currentService instanceof IDisposable) { 155 final IDisposable disposable = (IDisposable) currentService; 156 disposable.dispose(); 157 } 158 } 159 160 if (service == null) { 161 if (services.isEmpty()) { 162 services = null; 163 } 164 } else { 165 services.put(api, service); 166 } 167 } 168 169 } 170 | Popular Tags |