什么设计模式或反模式?

4
我将描述我想要做的事情,希望有人能告诉我这是什么设计模式或指出更好的替代方案。
我有一个方法来完成一堆涉及近似的复杂工作。虽然可以计算出结果而不使用近似,但这需要更多的工作。
我想要做的是得到一些与实现内部操作相关的比较。我的想法是传入一个对象来执行这个额外的工作,并存储关于比较的信息。
我认为我想从以下内容开始:
class Classifier(object):
    ...
    def classify(self, data):
        # Do some approximate stuff with the data and other
        # instance members.

to

class TruthComparer(object):
    def compute_and_store_stats(self, data, accessory_data):
        # Do the exact computation, compare to the approximation,
        # and store it.

    def get_comparison_stats(self):
        # Return detailed and aggregate information about the
        # differences between the truth and the approximation.

class Classifier(object):
    ...
    def classify(self, data, truth_comparer=None):
        # Do some approximate stuff with the data and other
        # instance members.
        # Optionally, do exact stuff with the data and other
        # instance members, storing info about differences
        # between the exact computation and the approximation
        # in the truth_comparer
        if truth_comparer is not None:
            truth_comparer.compute_and_store_stats(data,
                                                   [self._index, self._model],
                                                   intermediate_approximation)

我不想在classify方法内联做这些比较,因为我认为这些比较不适合该方法或对象的工作。

那么,这是哪种设计模式呢?你能提供一种替代方案吗?

2个回答

2
您可以使用 装饰器模式。您需要定义一个 Classifier 接口,并使用从 Classifier 继承的 TruthComparerDecorator。一个装饰器,即 TruthComparer,以 Classifier 为输入,使用此分类器实例计算近似值,然后运行 compute_and_store_stats 方法。使用此模式,分类器不需要了解有关 TruthComparer 的任何信息。最终,TruthComparer 是一个 Classifier,但执行更多操作。在Java中,代码可能如下所示:

public interface Classifier {
    void classify(Data data);
}

public abstract class TruthComparer implements Classifier {
    private Classifier classifier;
    public TruthComparerDecorator(Classifier classifier) {
        this.classifier = classifier;
    }
    public void classify(Data data) {
        classifier.classify(data);
        computeAndStoreStats(data);
    }
    public abstract void computeAndStoreStats(Data data);
}

0

我对你提出的更改有问题,因为分类器请求计算和存储统计信息部分似乎不正确。分类器不应该真正关心这个。理想情况下,它甚至不应该知道TruthComparer的存在。

我建议在分类器上真正需要两种方法:classify/classify_exact。Classify返回近似结果;classify_exact返回精确结果。不要将TruthComparer作为参数传递,而是将两个分类给TruthComparer并让它完成其工作。

这样可以减少分类器处理的对象数量(降低耦合),我认为可以更清楚地说明正在发生的事情。


我确实省略了一些细节。我想要比较的并不是最终结果,而是要收集关于计算中使用的某些中间值的统计数据。由近似分类器生成的中间值使用传递给方法的数据以及其他一些实例成员,这些成员对于精确分类器来说是不可用的(因为它们不需要)。 - user334856
1
在这种情况下,我可能会让我的分类方法返回一个包含分类结果和额外数据的对象。然后我会把它传递给TruthComparer。(总之,你的设计没有什么问题) - Winston Ewert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接