Skip to content

Commit 5be0206

Browse files
committed
readme added
1 parent 766d14a commit 5be0206

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

binding-property/README.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Binding Properties Pattern
2+
3+
## Intent
4+
Synchronize state between objects with automatic updates, enabling one-way or two-way data binding.
5+
6+
## Explanation
7+
8+
This pattern is used to ensure that changes in one component (like a data model) are reflected in another component (like a UI element) automatically, and vice versa.
9+
10+
### Participants
11+
1. **ObservableProperty**: Holds the value and notifies observers when it changes.
12+
2. **Observer**: Defines the interface for objects that respond to observable property changes.
13+
3. **TextView**: Implements the `Observer` interface and simulates a UI component.
14+
15+
### Applicability
16+
- Synchronizing state between multiple objects.
17+
- Minimizing boilerplate code for updates.
18+
19+
### Example Code
20+
```java
21+
22+
public class ObservableProperty<T> {
23+
private T value;
24+
private final List<Observer<T>> observers = new ArrayList<>();
25+
private boolean isUpdating = false;
26+
27+
public ObservableProperty(T initialValue) {
28+
this.value = initialValue;
29+
}
30+
31+
public T getValue() {
32+
return value;
33+
}
34+
35+
public void setValue(T value) {
36+
if (isUpdating || this.value == value || (this.value != null && this.value.equals(value))) {
37+
return;
38+
}
39+
this.value = value;
40+
notifyObservers();
41+
}
42+
43+
public void addObserver(Observer<T> observer) {
44+
observers.add(observer);
45+
observer.bind(this);
46+
}
47+
48+
public void removeObserver(Observer<T> observer) {
49+
observers.remove(observer);
50+
observer.unbind();
51+
}
52+
53+
private void notifyObservers() {
54+
for (Observer<T> observer : observers) {
55+
isUpdating = true;
56+
observer.update(value);
57+
isUpdating = false;
58+
}
59+
}
60+
}
61+
// TextView reacts to the change

0 commit comments

Comments
 (0)