1 """CompositePattern in DesignPatterns Example
   2 """
   3 
   4 import unittest
   5 
   6 class Pipe:
   7     def __init__(self,aNumber=None):
   8         self._number=aNumber
   9     def putIn(self,aNumber):
  10         raise NotImplementedError
  11 
  12 class CompositePipe(Pipe):
  13     def setChildren(self,*aPipes):
  14         self._childrenPipes=aPipes
  15     
  16 class SequencePipe(CompositePipe):
  17     def putIn(self,aNumber):
  18         v=aNumber
  19         for eachPipe in self._childrenPipes:
  20             v=eachPipe.putIn(v)
  21         return v
  22 
  23 class ParallelPipe(CompositePipe):
  24     def putIn(self,aNumber):
  25         pass
  26         
  27 class AddPipe(Pipe):
  28     def putIn(self,aNumber):
  29         return aNumber+self._number
  30 
  31 class MultiplyPipe(Pipe):
  32     def putIn(self,aNumber):
  33         return aNumber*self._number
  34     
  35 class TestPipe(unittest.TestCase):
  36     def test1(self):
  37         addOne=AddPipe(1)
  38         self.assertEquals(0+1,addOne.putIn(0))
  39         double=MultiplyPipe(2)
  40         self.assertEquals(1*2,double.putIn(1))
  41         addOneAndDouble=SequencePipe()
  42         addOneAndDouble.setChildren(addOne,double)
  43         self.assertEquals((2+1)*2,addOneAndDouble.putIn(2))
  44         addOneAndTwoDouble=SequencePipe()
  45         addOneAndTwoDouble.setChildren(addOneAndDouble,double)
  46         self.assertEquals((2+1)*2*2,addOneAndTwoDouble.putIn(2))
  47         
  48 if __name__=='__main__':
  49     unittest.main(argv=('','-v'))
web biohackers.net