Remove @author tags
[Sone.git] / src / main / java / net / pterodactylus / sone / utils / DefaultOption.java
1 package net.pterodactylus.sone.utils;
2
3 import com.google.common.base.Predicate;
4
5 /**
6  * Basic implementation of an {@link Option}.
7  *
8  * @param <T>
9  *            The type of the option
10  */
11 public class DefaultOption<T> implements Option<T> {
12
13         /** The default value. */
14         private final T defaultValue;
15
16         /** The current value. */
17         private volatile T value;
18
19         /** The validator. */
20         private Predicate<T> validator;
21
22         /**
23          * Creates a new default option.
24          *
25          * @param defaultValue
26          *            The default value of the option
27          */
28         public DefaultOption(T defaultValue) {
29                 this(defaultValue, null);
30         }
31
32         /**
33          * Creates a new default option.
34          *
35          * @param defaultValue
36          *            The default value of the option
37          * @param validator
38          *            The validator for value validation (may be {@code null})
39          */
40         public DefaultOption(T defaultValue, Predicate<T> validator) {
41                 this.defaultValue = defaultValue;
42                 this.validator = validator;
43         }
44
45         /**
46          * {@inheritDoc}
47          */
48         @Override
49         public T get() {
50                 return (value != null) ? value : defaultValue;
51         }
52
53         /**
54          * Returns the real value of the option. This will also return an unset
55          * value (usually {@code null})!
56          *
57          * @return The real value of the option
58          */
59         @Override
60         public T getReal() {
61                 return value;
62         }
63
64         /**
65          * {@inheritDoc}
66          */
67         @Override
68         public boolean validate(T value) {
69                 return (validator == null) || (value == null) || validator.apply(value);
70         }
71
72         /**
73          * {@inheritDoc}
74          */
75         @Override
76         public void set(T value) {
77                 if ((value != null) && (validator != null) && (!validator.apply(value))) {
78                         throw new IllegalArgumentException("New Value (" + value + ") could not be validated.");
79                 }
80                 this.value = value;
81         }
82
83 }