【问题标题】:Handling Complex Dependencies Between Object Properties (Auto Update Dependent Properties)处理对象属性之间的复杂依赖关系(自动更新依赖属性)
【发布时间】:2014-05-27 01:12:34
【问题描述】:

我有一个对象的树形结构,它们的属性对周围的对象有非常复杂的依赖关系,由它们在树中的位置决定。我已经硬编码了很多这些依赖项,并尝试创建某种更新循环(如果一个属性被更新,根据设计,所有依赖它的属性都会更新,并且以正确的顺序),但我想以更通用/抽象的方式处理它,而不是硬编码一堆对不同对象的更新调用。

假设,例如,我有 1 个超类和 3 个子类,然后是一个单独的容器对象。

形状
属性:parentContainer、index、left、top、width、height
方法:updateLeft()、updateTop()、updateWidth()、updateHeight()

Square 继承自 Shape
三角形继承自 Shape
Circle 继承自 Shape

ShapeContainer
属性:形状
方法:addShape(shape, index), removeShape(index)

我将给出一个伪代码示例更新方法来说明这些依赖项是如何出现的:

Square.updateTop() {
    var prevShape = null;
    if (this.index != 0) {
        prevShape = this.parentContainer.shapes[this.index - 1];
    }
    var nextSquareInContainer = null;
    for (var i = this.index; i < this.parentContainer.shapes.length; i++) {
        var shape = this.parentContainer.shapes[i];
        if(shape instanceof Square) {
            nextSquareInContainer = shape;
            break;
        }
    }
    var top = 0;
    if (prevShape != null && nextSquareInContainer != null) {
        top = prevShape.top + nextSquareInContainer.width;
    } else {
        top = 22;
    }
    this.top = top;
}  

因此,添加到 shapeConatiner 的任何正方形对象都将取决于前一个形状的顶部值以及容器宽度值中找到的下一个正方形的顶部值。

这里是一些设置示例形状容器的代码:

var shapeContainer = new ShapeContainer();
var triangle = new Triangle();
var circle = new Circle();
var square1 = new Square();
var square2 = new Square();
shapeContainer.addShape(triangle, 0);
shapeContainer.addShape(circle, 1);
shapeContainer.addShape(square1, 2);
shapeContainer.addShape(square2, 3);

所以,我想问题的症结在于,如果我更新上述圆的顶部值,我希望 square1 的顶部值能够自动更新(因为 square1 的顶部值和圆的顶部之间存在单向依赖关系价值)。所以我可以做到这一点的一种方法(我一直在做的方式,结合我的问题领域的一些其他特定知识来简化调用)是将类似于以下的代码添加到 Circle 的 updateTop 方法中(真的必须添加到每个形状的 updateTop 方法中):

Circle.updateTop() {
    // Code to actually calculate and update Circle's top value, note this
    // may depend on its own set of dependencies
    var nextShape = this.parentContainer.shapes[this.index + 1];
    if (nextShape instanceof Square) {
        nextShape.updateTop();
    }
}

这种类型的设计适用于对象之间的一些简单依赖关系,但我的项目有几十种类型的对象,它们的属性之间可能有数百个依赖关系。我是这样编码的,但是在尝试添加新功能或解决错误时很难推理。

是否存在某种设计模式来设置对象属性之间的依赖关系,然后当更新一个属性时,它会更新依赖它的其他对象上的所有属性(这可能会触发属性的进一步更新这取决于现在新更新的属性)?用于指定这些依赖项的某种声明性语法可能最适合可读性/可维护性。

另一个问题是,一个属性可能有多个依赖项,在我希望该属性自行更新之前,必须先更新所有依赖项。

我一直在研究 pub/sub 类型的解决方案,但我认为这是一个足够复杂的问题,需要寻求帮助。作为旁注,我正在使用 javascript。

【问题讨论】:

标签: javascript algorithm oop design-patterns dependencies


【解决方案1】:

这是我想出的骇人听闻的解决方案。我创建了一个包装类,您可以将匿名函数传递给 getter/setter/updaters。然后调用 prop1.dependsOn(prop2) 以声明方式设置依赖项。它涉及建立对象属性之间依赖关系的有向无环图,然后在更新属性值时,显式调用以使用拓扑排序解决相关依赖关系。我没有过多考虑效率,我敢打赌有人可以想出一个更强大/性能更高的解决方案,但我认为现在就可以了。抱歉代码转储,但我认为它可能对试图解决类似问题的人有所帮助。如果有人想让这个语法更干净,请成为我的客人。

// This is a class that will act as a wrapper for all properties 
// that we want to tie to our dependency graph.
function Property(initialValue, ctx) {
    // Each property will get a unique id.
    this.id = (++Property.id).toString();
    this.value = initialValue;
    this.isUpdated = false;
    this.context = ctx;
    Property.dependsOn[this.id] = [];
    Property.isDependedOnBy[this.id] = [];
    Property.idMapping[this.id] = this;
}
// Static properties on Property function.
Property.id = 0;
Property.dependsOn = {};
Property.isDependedOnBy = {};
Property.idMapping = {};

// Calling this updates all dependencies from the node outward.
Property.resolveDependencies = function (node) {
    node = node.id;
    var visible = [];
    // Using Depth First Search to mark visibility (only want to update dependencies that are visible).
    var depthFirst = function (node) {
        visible.push(node);
        for (var i = 0; i < Property.isDependedOnBy[node].length; i++) {
            depthFirst(Property.isDependedOnBy[node][i]);
        }
    };
    depthFirst(node);
    // Topological sort to make sure updates are done in the correct order.
    var generateOrder = function (inbound) {
        var noIncomingEdges = [];
        for (var key in inbound) {
            if (inbound.hasOwnProperty(key)) {
                if (inbound[key].length === 0) {
                    // Only call update if visible.
                    if (_.indexOf(visible, key) !== -1) {
                        Property.idMapping[key].computeValue();
                    }
                    noIncomingEdges.push(key);
                    delete inbound[key];
                }
            }
        }

        for (var key in inbound) {
            if (inbound.hasOwnProperty(key)) {
                for (var i = 0; i < noIncomingEdges.length; i++) {
                    inbound[key] = _.without(inbound[key], noIncomingEdges[i]);
                }
            }
        }

        // Check if the object has anymore nodes.
        for (var prop in inbound) {
            if (Object.prototype.hasOwnProperty.call(inbound, prop)) {
                generateOrder(inbound);
            }
        }

    };
    generateOrder(_.clone(Property.dependsOn));
};
Property.prototype.get = function () {
    return this.value;
}
Property.prototype.set = function (value) {
    this.value = value;
}
Property.prototype.computeValue = function () {
    // Call code that updates this.value.
};
Property.prototype.dependsOn = function (prop) {
    Property.dependsOn[this.id].push(prop.id);
    Property.isDependedOnBy[prop.id].push(this.id);
}

function PropertyFactory(methodObject) {
    var self = this;
    var PropType = function (initialValue) {
        Property.call(this, initialValue, self);
    }
    PropType.prototype = Object.create(Property.prototype);
    PropType.prototype.constructor = PropType;
    if (methodObject.get !== null) {
        PropType.prototype.get = methodObject.get;
    }
    if (methodObject.set !== null) {
        PropType.prototype.set = methodObject.set;
    }
    if (methodObject.computeValue !== null) {
        PropType.prototype.computeValue = methodObject.computeValue;
    }

    return new PropType(methodObject.initialValue);
}

以下是设置属性的示例:

function MyClassContainer() {
    this.children = [];
    this.prop = PropertyFactory.call(this, {
        initialValue: 0,
        get: null,
        set: null,
        computeValue: function () {
            var self = this.context;
            var updatedVal = self.children[0].prop.get() + self.children[1].prop.get();
            this.set(updatedVal);
        }
    });
}
MyClassContainer.prototype.addChildren = function (child) {
    if (this.children.length === 0 || this.children.length === 1) {
        // Here is the key line.  This line is setting up the dependency between
        // object properties.
        this.prop.dependsOn(child.prop);
    }
    this.children.push(child);
}

function MyClass() {
    this.prop = PropertyFactory.call(this, {
        initialValue: 5,
        get: null,
        set: null,
        computeValue: null
    });
}

var c = new MyClassContainer();
var c1 = new MyClass();
var c2 = new MyClass();
c.addChildren(c1);
c.addChildren(c2);

这是一个在所有基础设施设置完成后实际更新属性的示例:

c1.prop.set(3);
Property.resolveDependencies(c1.prop);

我觉得对于需要非常复杂的依赖项的程序来说,这是一个非常强大的模式。 Knockout JS 有类似的东西,与 computedObservables(它们以类似的方式使用包装器),但据我所知,您只能将计算属性与同一对象上的其他属性联系起来。上述模式允许您将对象属性任意关联为依赖项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多