001/* Copyright (C) 2013 TU Dortmund 002 * This file is part of AutomataLib, http://www.automatalib.net/. 003 * 004 * AutomataLib is free software; you can redistribute it and/or 005 * modify it under the terms of the GNU Lesser General Public 006 * License version 3.0 as published by the Free Software Foundation. 007 * 008 * AutomataLib is distributed in the hope that it will be useful, 009 * but WITHOUT ANY WARRANTY; without even the implied warranty of 010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 011 * Lesser General Public License for more details. 012 * 013 * You should have received a copy of the GNU Lesser General Public 014 * License along with AutomataLib; if not, see 015 * http://www.gnu.de/documents/lgpl.en.html. 016 */ 017package net.automatalib.commons.util.nid; 018 019import java.util.Iterator; 020import java.util.LinkedList; 021import java.util.List; 022 023import net.automatalib.commons.util.ref.Ref; 024import net.automatalib.commons.util.ref.StrongRef; 025import net.automatalib.commons.util.ref.WeakRef; 026 027 028public class IDChangeNotifier<T extends NumericID> { 029 private final List<Ref<IDChangeListener<T>>> listeners 030 = new LinkedList<Ref<IDChangeListener<T>>>(); 031 032 public void addListener(IDChangeListener<T> listener, boolean weak) { 033 Ref<IDChangeListener<T>> ref; 034 if(weak) 035 ref = new WeakRef<IDChangeListener<T>>(listener); 036 else 037 ref = new StrongRef<IDChangeListener<T>>(listener); 038 039 listeners.add(ref); 040 } 041 042 public void removeListener(IDChangeListener<T> listener) { 043 if(listener == null) 044 return; 045 046 Iterator<? extends Ref<?>> it = listeners.iterator(); 047 048 while(it.hasNext()) { 049 Object referent = it.next().get(); 050 if(referent == null) 051 it.remove(); 052 else if(referent.equals(listener)) 053 it.remove(); 054 } 055 } 056 057 public void notifyListeners(T obj, int newId, int oldId) { 058 Iterator<Ref<IDChangeListener<T>>> it 059 = listeners.iterator(); 060 061 while(it.hasNext()) { 062 IDChangeListener<T> listener = it.next().get(); 063 if(listener == null) 064 it.remove(); 065 else 066 listener.idChanged(obj, newId, oldId); 067 } 068 } 069}