view src/org/tmatesoft/hg/internal/AdapterPlug.java @ 587:a52f4cc56f9c

Minimize vectors re-allocating when merging patches
author Artem Tikhomirov <tikhomirov.artem@gmail.com>
date Fri, 26 Apr 2013 20:04:17 +0200
parents 90df078d6418
children
line wrap: on
line source
/*
 * Copyright (c) 2012-2013 TMate Software Ltd
 *  
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * For information on how to redistribute this software under
 * the terms of a license other than GNU General Public License
 * contact TMate Software at support@hg4j.com
 */
package org.tmatesoft.hg.internal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.tmatesoft.hg.util.Adaptable;

/**
 * Implementation of {@link Adaptable} that allows to add ("plug")
 * adapters as needed
 * 
 * @author Artem Tikhomirov
 * @author TMate Software Ltd.
 */
public class AdapterPlug implements Adaptable {
	private final Map<Class<?>, Object> adapters = new HashMap<Class<?>, Object>();
	private final List<Class<?>> adapterUses = new ArrayList<Class<?>>();
	
	public <T> void attachAdapter(Class<T> adapterClass, T instance) {
		adapters.put(adapterClass, instance);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T detachAdapter(Class<T> adapterClass) {
		return (T) adapters.remove(adapterClass);
	}

	public <T> T getAdapter(Class<T> adapterClass) {
		Object instance = adapters.get(adapterClass);
		if (instance != null) {
			adapterUses.add(adapterClass);
			return adapterClass.cast(instance);
		}
		return null;
	}
	
	public int getAdapterUse(Class<?> adapterClass) {
		int uses = 0;
		for (Class<?> c : adapterUses) {
			if (c == adapterClass) {
				uses++;
			}
		}
		return uses;
	}
}