复合模式逆序函数调用

时间:2017-03-18 15:43:39

标签: python inheritance composite

我有这样的复合课程。我想以相反的顺序调用组件函数。我的意思是第一个最深的子函数被调用,然后是一个级别,依此类推。

在下面的例子中,我根据他们的孩子计算复合物体的重量。因此,首先计算儿童体重,然后根据儿童体重计算父体重。

我该怎么做?我应该使用哪种模式或算法?

class Component(object): 
    def __init__(self,desc,weight, *args, **kw):
        self.parent = None
        self.desc = desc
        self.weight_user_defined = weight
    def component_function(self):
        pass
    def setParent(self,parent):
        self.parent=parent

class Leaf(Component):
    def __init__(self,desc,weight,*args, **kw):
        Component.__init__(self,desc,weight, *args, **kw)

    def component_function(self):
        print (self.desc,self.weight_user_defined)

class Composite(Component):
    def __init__(self,desc,weight, *args, **kw):
        Component.__init__(self,desc,weight,*args, **kw)
        self.children = []
        self.weight_calculated = 0.0

    def append_child(self, child):
        self.children.append(child)
        child.setParent(self)

    def remove_child(self, child):
        self.children.remove(child)

    def component_function(self):      
        print (self.desc,self.weight_user_defined)
        for foo in self.children:
            foo.component_function()

举个例子:

ROOT (X kg)
    GLOCARY (Y kg)
        Apple  2.1 kg
        Banana 3.2 kg
    MISC (Z kg)  
        Stuff1 3.3 kg
        Stuff2 0.7 kg

因此,为了找到X,Y和Z首先计算出来。 (或者可能是叶子。例如,数量*项目价格)

1 个答案:

答案 0 :(得分:0)

注意:我不确定你的意思是"逆序函数调用",但这就是你如何计算基于的复合权重孩子。

没有孩子的Composite将永远有weight=0。我没有想到Composite在没有孩子的情况下拥有weight!=0会有意义。

添加孩子时,请将孩子的体重添加到Composite的体重中。移除孩子时,减去其重量。

class Component(object): 
    def __init__(self,desc,weight=0,*args,**kw):
        self.parent = None
        self.desc = desc
        self.weight = weight

    def setParent(self,parent):
        self.parent=parent

    def getWeight(self):
        raise NotImplementedError("Must instantiate subclass")

class Leaf(Component):
    def getWeight(self):
        return self.weight

class Composite(Component):
    def __init__(self,desc, *args, **kw):
        super(Composite,self).__init__(desc,*args, **kw)
        self.children = []

    def append_child(self, child):
        self.children.append(child)
        child.setParent(self)
        self.weight += child.getWeight()

    def remove_child(self, child):
        self.children.remove(child)
        self.weight -= child.getWeight()

    def getWeight(self):
        return self.weight

在此,我通过将LeafComposite s添加为另一个Composite的子项来演示。

c1 = Composite("Composite 1")
c2 = Composite("Composite 2")

c1.append_child(Leaf("A leaf",5))
c1.append_child(Leaf("A leaf",5))
c1.append_child(Leaf("A leaf",5))

c2.append_child(Leaf("A leaf",1))
c2.append_child(Leaf("A leaf",1))
c2.append_child(Leaf("A leaf",1))

c1.append_child(c2)

输出

In [2]: print(c1.getWeight())
18

In [3]: c1.remove_child(c2)
   ...: print(c1.getWeight())
   ...: 
15