Skip to content

Binding property module added #3144

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions binding-property/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Binding Properties Pattern

## Intent
Synchronize state between objects with automatic updates, enabling one-way or two-way data binding.

## Explanation

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.

### Participants
1. **ObservableProperty**: Holds the value and notifies observers when it changes.
2. **Observer**: Defines the interface for objects that respond to observable property changes.
3. **TextView**: Implements the `Observer` interface and simulates a UI component.

### Applicability
- Synchronizing state between multiple objects.
- Minimizing boilerplate code for updates.

### Example Code
```java

public class ObservableProperty<T> {
private T value;
private final List<Observer<T>> observers = new ArrayList<>();
private boolean isUpdating = false;

public ObservableProperty(T initialValue) {
this.value = initialValue;
}

public T getValue() {
return value;
}

public void setValue(T value) {
if (isUpdating || this.value == value || (this.value != null && this.value.equals(value))) {
return;
}
this.value = value;
notifyObservers();
}

public void addObserver(Observer<T> observer) {
observers.add(observer);
observer.bind(this);
}

public void removeObserver(Observer<T> observer) {
observers.remove(observer);
observer.unbind();
}

private void notifyObservers() {
for (Observer<T> observer : observers) {
isUpdating = true;
observer.update(value);
isUpdating = false;
}
}
}
// TextView reacts to the change
35 changes: 35 additions & 0 deletions binding-property/etc/binding.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
@startuml
title Two-Way Binding Properties Pattern - Class Diagram

class ObservableProperty {
- value : T
- observers : List<Observer<T>>
- isUpdating : boolean
+ ObservableProperty(initialValue : T)
+ getValue() : T
+ setValue(value : T)
+ addObserver(observer : Observer<T>)
+ removeObserver(observer : Observer<T>)
- notifyObservers()
}

interface Observer {
+ update(newValue : T)
+ bind(observableProperty : ObservableProperty<T>)
+ unbind()
}

class TextView {
- text : String
- observableProperty : ObservableProperty<String>
+ update(newValue : String)
+ bind(observableProperty : ObservableProperty<String>)
+ unbind()
+ setText(newText : String)
+ getText() : String
}

ObservableProperty "1" o-- "*" Observer
Observer <|-- TextView

@enduml
67 changes: 67 additions & 0 deletions binding-property/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).

The MIT License
Copyright © 2014-2022 Ilkka Seppälä

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>
<artifactId>bridge</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.binding.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
23 changes: 23 additions & 0 deletions binding-property/src/main/java/com/iluwatar/binding/App.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.iluwatar.binding;

public class App {
public static void main(String[] args) {
ObservableProperty<String> observableProperty = new ObservableProperty<>("Initial Value");
TextView textView = new TextView();

// Bind TextView to ObservableProperty
observableProperty.addObserver(textView);

// Update ObservableProperty
System.out.println("Setting value in ObservableProperty...");
observableProperty.setValue("Hello, Design Patterns!");

// Simulate user input through TextView
System.out.println("User updates TextView...");
textView.setText("User Input!");

// Set another value in ObservableProperty to observe two-way binding
System.out.println("Setting another value in ObservableProperty...");
observableProperty.setValue("Two-Way Binding Works!");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.iluwatar.binding;

import java.util.ArrayList;
import java.util.List;

public class ObservableProperty<T> {
private T value;
private final List<Observer<T>> observers = new ArrayList<>();
private boolean isUpdating = false;

public ObservableProperty(T initialValue) {
this.value = initialValue;
}

public T getValue() {
return value;
}

public void setValue(T value) {
if (isUpdating || this.value == value || (this.value != null && this.value.equals(value))) {
return;
}
this.value = value;
notifyObservers();
}

public void addObserver(Observer<T> observer) {
observers.add(observer);
observer.bind(this);
}

public void removeObserver(Observer<T> observer) {
observers.remove(observer);
observer.unbind();
}

private void notifyObservers() {
for (Observer<T> observer : observers) {
isUpdating = true;
observer.update(value);
isUpdating = false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.iluwatar.binding;

public interface Observer<T> {
void update(T newValue);

void bind(ObservableProperty<T> observableProperty);

void unbind();
}
44 changes: 44 additions & 0 deletions binding-property/src/main/java/com/iluwatar/binding/TextView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.iluwatar.binding;

public class TextView implements Observer<String> {
private String text;
private ObservableProperty<String> boundProperty;

@Override
public void update(String newValue) {
// Prevent unnecessary updates
if (text != null && text.equals(newValue)) {
return;
}
this.text = newValue;
System.out.println("TextView updated: " + text);
}

@Override
public void bind(ObservableProperty<String> observableProperty) {
// Unbind from the current property if already bound
if (this.boundProperty != null) {
this.boundProperty.removeObserver(this);
}
this.boundProperty = observableProperty;
}

@Override
public void unbind() {
if (this.boundProperty != null) {
this.boundProperty.removeObserver(this);
this.boundProperty = null;
}
}

public void setText(String newText) {
if (boundProperty != null) {
boundProperty.setValue(newText);
}
this.text = newText;
}

public String getText() {
return text;
}
}
16 changes: 16 additions & 0 deletions binding-property/src/test/java/com/iluwatar/binding/AppTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.iluwatar.binding;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;

public class AppTest {

@Test
public void testAppRunsWithoutExceptions() {
assertDoesNotThrow(() -> {
com.iluwatar.binding.App.main(new String[]{});
});
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.iluwatar.binding;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class ObservablePropertyTest {

@Test
public void testNotifyObservers() {
ObservableProperty<String> observableProperty = new ObservableProperty<>("Initial");
TestObserver testObserver = new TestObserver();
observableProperty.addObserver(testObserver);

observableProperty.setValue("Updated");

assertEquals("Updated", testObserver.getReceivedValue());
}

private static class TestObserver implements Observer<String> {
private String receivedValue;

@Override
public void update(String newValue) {
receivedValue = newValue;
}

@Override
public void bind(ObservableProperty<String> observableProperty) {
// No binding logic needed for this test.
}

@Override
public void unbind() {
// No unbinding logic needed for this test.
}

public String getReceivedValue() {
return receivedValue;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.iluwatar.binding;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class TextViewTest {

@Test
public void testTextViewUpdatesFromObservable() {
ObservableProperty<String> observableProperty = new ObservableProperty<>("Initial");
TextView textView = new TextView();

// Bind TextView to ObservableProperty
observableProperty.addObserver(textView);

// Change observable value
observableProperty.setValue("New Value");

assertEquals("New Value", textView.getText());
}

@Test
public void testTextViewUpdatesObservable() {
ObservableProperty<String> observableProperty = new ObservableProperty<>("Initial");
TextView textView = new TextView();

// Bind TextView to ObservableProperty
observableProperty.addObserver(textView);

// Simulate user updating TextView
textView.setText("User Input");

assertEquals("User Input", observableProperty.getValue());
}
}
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
<module>prototype</module>
<module>singleton</module>
<module>adapter</module>
<module>binding-property</module>
<module>bridge</module>
<module>composite</module>
<module>data-access-object</module>
Expand Down
Loading