package org.zact.idk.cache;

import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author <a href="mailto:colus@isoft.co.kr">Eung-ju Park</a>
 */
public abstract class AbstractCache
    implements Cache
{
    protected ArrayList m_listeners;

    public AbstractCache()
    {
        m_listeners = new ArrayList();
    }

    public void addCacheListener( final CacheListener listener )
    {
        synchronized ( m_listeners )
        {
            m_listeners.add( listener );
        }
    }

    public void removeCacheListener( final CacheListener listener )
    {
        synchronized ( m_listeners )
        {
            m_listeners.remove( listener );
        }
    }

    protected void notifyEvent( final Object key, final Object value,
                                final int type )
    {
        final CacheEvent event = new CacheEvent( this, key, value, type );

        ArrayList l;
        synchronized ( m_listeners )
        {
            l = (ArrayList)m_listeners.clone();
        }

        final int s = l.size();
        for ( int i = 0; i < s; i++ )
        {
            ((CacheListener)l.get( i )).cacheEvent( event );
        }
    }

    protected void notifyAdded( final Object key, final Object value )
    {
        notifyEvent( key, value, CacheEvent.ADDED );
    }

    protected void notifyRemoved( final Object key, final Object value )
    {
        notifyEvent( key, value, CacheEvent.REMOVED );
    }
}
