common-utils/src/main/java/org/warp/commonutils/type/BiAssociation.java

124 lines
2.4 KiB
Java

package org.warp.commonutils.type;
import it.unimi.dsi.fastutil.objects.ObjectSet;
import java.util.Optional;
/**
* One to one relationship
*
* o ------- o
* o ------- o
* o ------- o
* o ------- o
* o ------- o
* o ------- o
* o ------- o
* o ------- o
*
* @param <T> Source type
* @param <U> Destination type
*/
public interface BiAssociation<T, U> {
/**
* Link source to dest
* @param src Source
* @param dest Destination
* @return previous value if it was already linked
*/
Optional<U> link(T src, U dest);
/**
* Unlink only if src is linked with dest
* @param src Source
* @param dest Destination
* @return true if unlinked, false if not present
*/
boolean unlink(T src, U dest);
/**
* Unlink
* @param src Source
* @return previous linked destination
*/
Optional<U> unlink(T src);
/**
* Unlink
* @param dest Destination
* @return previous linked source
*/
Optional<T> unlinkFromSource(U dest);
/**
* Check if link exists
* @param src Source
* @return true if source it's linked with a destination
*/
default boolean hasLink(T src) {
return getLink(src).isPresent();
}
/**
* Check if link exists
* @param dest Destination
* @return true if destination is linked with a source
*/
default boolean hasLinkSource(U dest) {
return getLinkSource(dest).isPresent();
}
/**
* Check if link exists
* @param src Source
* @param dest Destination
* @return true if source and destination are linked together
*/
boolean hasLink(T src, U dest);
/**
* Get a link destination
* @param src Source
* @return Destination if the link exists
*/
Optional<U> getLink(T src);
/**
* Get a link source
* @param dest Source
* @return Source if the link exists
*/
Optional<T> getLinkSource(U dest);
/**
* Delete all links
*/
void clear();
/**
* Get the count of existing links
* @return size
*/
int size();
/**
* Get all the sources
* @return Set of sources
*/
ObjectSet<T> getSources();
/**
* Get all the destinations
* @return Set of destinations
*/
ObjectSet<U> getDestinations();
static <T, U> BiAssociation<T, U> synchronize(BiAssociation<T, U> association) {
return new SynchronizedBiAssociation(association);
}
static <T, U> BiAssociation<T, U> synchronize(BiAssociation<T, U> association, Object lock) {
return new SynchronizedBiAssociation(association, lock);
}
}