IronPython系列:Composite Pattern及其实现

  最近挺经常做鱼的。对于做鱼的步骤算是熟悉。以烤制为例,主要有三步:洗(Clean)、切(Cut)和烤(Bake)。烤鱼(Bake)又有两个小步:加热(Heat)和烤(Bake)。软件开发也是这样,整个软件开发生命周期(SDLC)也几个大阶段,每个大阶段可能还可以细分成几个小阶段。层次感体现了美感。这就是Composite Pattern。如果知道做鱼各个具体步骤的耗时,总耗是多少呢?这么简单的问题口算就可以,不过这回“杀机用牛刀”下,利用该模式的IronPython的实现如下:
class Task(object):
        def __init__(self, name, time):    
                self.name = name    
                self.parent = None
                self.time = time
        def get_time_required(self):    
                return self.time

class CompositeTask(Task):
        def __init__(self, name):
                Task.__init__(self, name, 0)
                self.sub_tasks = []
        def get_time_required(self):
                return sum(t.get_time_required() for t in self.sub_tasks)
        def add_sub_task(self, task):
                self.sub_tasks.append(task)
                task.parent = self
        def remove_sub_task(self, task):
                self.sub_tasks.remove(task)
        def __getitem__(self, i):
                return self.sub_tasks[i]

if __name__ == "__main__":
        cookFish = CompositeTask("Cook Fish")
        cleanFish = Task("cleanFish", 5)
        cookFish.add_sub_task(cleanFish)
        cutFish = Task("Cut Fish", 7)
        cookFish.add_sub_task(cutFish)
        bakeFish = CompositeTask("Bake Fish")
        cookFish.add_sub_task(bakeFish)
        heatPan = Task("Heat Pan", 5)
        bakeFish.add_sub_task(heatPan)
        bake = Task("Bake", 5)
        bakeFish.add_sub_task(bake)
        print "Finish all tasks in", cookFish.get_time_required(), "minutes"

  其中,Task代表具体步骤,CompositeTask是由若干步骤(具体步骤或组合步骤)组成的复合步骤。

你可能感兴趣的:(Pattern,职场,IronPython,休闲,composite)