Update Programming Guide

2025-07-08 21:23:55 +02:00
parent 74c91ec314
commit 9e0c11a4bc

@@ -143,12 +143,44 @@ Or clear everything:
Ctx.INSTANCE.clear(); Ctx.INSTANCE.clear();
``` ```
## Multiple Named Contexts
You can create and manage multiple independent contexts identified by names.
```java
// Obtain or create named contexts
CtxInterface orderCtx = Ctx.INSTANCE.getContext("order");
CtxInterface userCtx = Ctx.INSTANCE.getContext("user");
// Define keys for each context
Key<String> orderIdKey = Key.of("orderId", String.class);
Key<String> userIdKey = Key.of("userId", String.class);
// Put values into separate contexts
orderCtx.put(orderIdKey, "ORD123");
userCtx.put(userIdKey, "USR456");
// Retrieve independently
String orderId = orderCtx.get(orderIdKey);
String userId = userCtx.get(userIdKey);
```
You can list all named contexts:
```java
Set<String> contexts = Ctx.INSTANCE.contextNames();
System.out.println("Active contexts: " + contexts);
```
Changes in one context do not affect others, allowing modular isolation of data.
## Best Practices ## Best Practices
* Define your keys as constants to keep them consistent * Define your keys as constants to keep them consistent
* Register listeners in classes that depend on context changes * Register listeners in classes that depend on context changes
* Remove listeners when no longer needed (though weak references help) * Remove listeners when no longer needed (though weak references help)
* Use unique key names to avoid collisions * Use unique key names to avoid collisions within each context
* Use multiple contexts to logically separate unrelated data
## Complete Example ## Complete Example
@@ -167,5 +199,7 @@ Ctx.INSTANCE.removeListener(temperatureKey, display);
Ctx.INSTANCE.put(temperatureKey, 30); // no notification after listener removed Ctx.INSTANCE.put(temperatureKey, 30); // no notification after listener removed
``` ```
--- ---
[[Home]] | [[API Reference]] | [[Design and Architecture]] | [[FAQ]] | [[Contributing]] [[Home]] | [[API Reference]] | [[Design and Architecture]] | [[FAQ]] | [[Contributing]]