All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cdc.applic.dictionaries.edit.EnAbstractOwnedElement Maven / Gradle / Ivy

There is a newer version: 0.13.3
Show newest version
package cdc.applic.dictionaries.edit;

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

import cdc.util.lang.Checks;

/**
 * Base class of owned elements (they have a owner).
 *
 * @author Damien Carbonne
 *
 * @param  The owner type. The concrete owner may derive from it.
 */
public abstract class EnAbstractOwnedElement extends EnAbstractElement implements EnOwnedElement {
    private O owner;

    protected EnAbstractOwnedElement(Builder builder) {
        super(builder.fixId());
        this.owner = Checks.isNotNull(builder.owner, EnNames.OWNER);
    }

    protected final void addToOwner() {
        ((EnAbstractElement) getOwner()).addChild(this);
    }

    private final void removeFromOwner() {
        ((EnAbstractElement) getOwner()).removeChild(this);
    }

    @Override
    public O getOwner() {
        return owner;
    }

    protected > EnRef getRef(Class elementClass) {
        return EnRef.of(getOwner(), elementClass, getId());
    }

    public abstract EnRef> getRef();

    /**
     * Recursively removes this element and its children.
     * 

* Children are removed first. */ public void remove() { final EnRepository repository = getRepository(); final List> todo = new ArrayList<>(getChildren()); for (final EnAbstractOwnedElement child : todo) { child.remove(); } removeFromOwner(); this.owner = null; repository.removeFromRepository(this); } public boolean isAlive() { return this.owner != null; } public boolean isDead() { return this.owner == null; } @Override public int getIndex() { return ((EnAbstractElement) owner).getChildIndex(this); } @Override public EnRepository getRepository() { return getOwner().getRepository(); } /** * Base builder of children elements. * * @author Damien Carbonne * * @param The builder type. * @param The built element type. * @param The concrete parent type. */ public abstract static class Builder, E extends EnAbstractOwnedElement, O extends EnElement> extends EnAbstractElement.Builder { protected final O owner; protected Builder(O owner) { this.owner = owner; } protected B fixId() { if (!hasId()) { id(getRepository().newId(getBuiltClass())); } return self(); } protected E wrap(E element) { return getRepository().addToRepository(element); } /** * @return The owner element. */ public O getOwner() { return owner; } /** * @return The root model. */ public EnRepository getRepository() { return owner.getRepository(); } protected X getItemWithId(String id, Class itemClass) { return getRepository().getElementWithId(id, itemClass); } /** * Build the element and returns its parent. * * @return The concrete parent of the built element. */ public O back() { build(); return owner; } } }