aboutsummaryrefslogtreecommitdiff
path: root/Week14 Route 66/src/OO14route66/Regelaar.java
blob: bf4cbfda065a9aeca7bf09766f772144aabf3351 (plain) (blame)
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
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package OO14route66;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author pieterkoopman
 */
public class Regelaar {
    
    private static Regelaar instance;
    
    Map<Car, Integer> locations;
    
    protected Regelaar() {
        locations = new HashMap<>();
    }
    
    public static Regelaar getInstance() {
        if (instance == null) {
            instance = new Regelaar();
        }
        return instance;
    }
    
    public synchronized void setLocation(Car car, int location) {
        if (locations.containsKey(car)) {
            locations.remove(car);
        } 
        locations.put(car, location);
    }
    
    public synchronized boolean isSafeLocation(Car car, int requested_location) {
        for (Map.Entry<Car, Integer> location : locations.entrySet()) {
            Car that_car = location.getKey();
            if (that_car != car && 
                    that_car.getDirection() == car.getDirection() &&
                    that_car.getLocation() > requested_location &&
                    that_car.getLocation() < requested_location + Car.CARLENGTH + Car.MINCARSPACE) {
                return false;
            }
        }
        return true;
    }

}