summaryrefslogtreecommitdiffstats
path: root/logo/src/xlogo/interfaces/PropertyChangePublisher.java
blob: a953b8c309486751ba7baf8149a2da9b9dc02a6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package xlogo.interfaces;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class PropertyChangePublisher<E extends Enum<E>> implements Observable<E>, Serializable {
	
	private static final long	serialVersionUID	= -1042512850782413412L;
	
	private boolean enableEvents = true;
	
	private final HashMap<E, List<PropertyChangeListener>>	listeners	= new HashMap<>();
	private final List<PropertyChangeListener> allPropertiesListeners = new ArrayList<>();
	
	@Override
	public void addPropertyChangeListener(E property, PropertyChangeListener listener) {
		if (listener == null){
			throw new IllegalArgumentException("Cannot add an event listeners that is null.");
		}
		
		if (property == null){
			allPropertiesListeners.add(listener);
			return;
		}
		List<PropertyChangeListener> list = listeners.get(property);
		if (list == null) {
			list = new ArrayList<>();
			listeners.put(property, list);
		}
		list.add(listener);
	}
	
	@Override
	public void removePropertyChangeListener(E property, PropertyChangeListener listener) {
		if (listener == null){
			throw new IllegalArgumentException("Cannot remove an event listeners that is null.");
		}
		
		if (property == null){
			allPropertiesListeners.remove(listener);
			return;
		}
		
		List<PropertyChangeListener> list = listeners.get(property);
		if(list != null){
			list.remove(listener);
		}
	}
	
	public void publishEvent(E property){
		if (!enableEvents){
			return;
		}
		setEnableEvents(false);
		if (listeners.containsKey(property))
			listeners.get(property).forEach((listener) -> listener.propertyChanged());
		allPropertiesListeners.forEach((listener) -> listener.propertyChanged());
		setEnableEvents(true);
	}

	public void setEnableEvents(boolean enableEvents) {
		this.enableEvents = enableEvents;
	}
	
}