#format python """FactoryMethodPattern in DesignPatterns Example """ import unittest class Room: def __init__(self,anId): self._id=anId def getConnectedRooms(self): return self._door.getTheOtherRoom(self._id) def setDoor(self,aDoor): self._door=aDoor def lookAround(self): return "it's a room" class FireRoom(Room): def lookAround(self): return "It's very hot" class IceRoom(Room): def lookAround(self): return "It's very cold" class Door: def __init__(self,aRoom1,aRoom2): self._room1=aRoom1 self._room2=aRoom2 self._room1.setDoor(self) self._room2.setDoor(self) def getTheOtherRoom(self,aRoomId): if aRoomId==self._room1._id: return self._room2 else: return self._room1 class FireDoor(Door): pass class IceDoor(Door): pass class Maze: def __init__(self): self.rooms=[] ## r1=Room(1) # FactoryMethod ## r2=Room(2) r1 = self.createRoom(1) r2 = self.createRoom(2) ## self.d=Door(r1,r2) # FactoryMethod self.d = self.createDoor(r1,r2) self.addRoom(r1) self.addRoom(r2) def addRoom(self,aRoom): self.rooms.append(aRoom) def getRooms(self): return self.rooms def getDoors(self): return [self.d,] def createRoom(self,anId): raise NotImplementedError def createDoor(self,aRoom1, aRoom2): raise NotImplementedError class FireMaze(Maze): def createRoom(self,anId): return FireRoom(anId) def createDoor(self, aRoom1, aRoom2): return FireDoor(aRoom1, aRoom2) class IceMaze(Maze): def createRoom(self,anId): return IceRoom(anId) def createDoor(self, aRoom1, aRoom2): return IceDoor(aRoom1, aRoom2) def makeMaze(aMazeType): if aMazeType == 'fire': return FireMaze() elif aMazeType == 'ice': return IceMaze() class TestMaze(unittest.TestCase): def testRoom(self): r1=Room(1) self.assert_(r1) def testDoor(self): r1=Room(1) r2=Room(2) d=Door(r1,r2) self.assert_(d) rooms=r1.getConnectedRooms() self.assertEquals(r2,rooms) def testMakeFireMaze(self): m=makeMaze('fire') r = m.getRooms()[0] self.assert_(isinstance(r,FireRoom)) d = m.getDoors()[0] self.assert_(isinstance(d,FireDoor)) expected = "It's very hot" self.assertEquals(expected ,r.lookAround()) def testMakeIceMaze(self): m=makeMaze('ice') r = m.getRooms()[0] self.assert_(isinstance(r,IceRoom)) d = m.getDoors()[0] self.assert_(isinstance(d,IceDoor)) expected = "It's very cold" self.assertEquals(expected ,r.lookAround()) if __name__=='__main__': unittest.main(argv=('','-v'))