2014-04-17 27 views
2

這是玩具問題處理多重構圖:Python的組成:在一個盒子裏的彈珠

有兩個對象類,代表彈珠和框。一個大理石總是包含在一個盒子裏,而一個盒子有一個用於表示當前在其中的大理石的類方法。大理石,一旦實例化,應該能夠傳遞給任何其他現有的盒子(或者甚至可能是另一個對象的可擴展性)。

在Python中實現多個'has-a'組合的最佳模式是什麼? (我發現單曲有一個例子,但沒有偶然發現一個多重作曲的例子)。

我的第一個猜測是,通過Box類中包含的方法(例如create_marble,pass_marble,delete_marble方法)來處理Marble對象,並在Box類中維護一個Marbles列表作爲屬性。但是,這真的是最好的方式嗎?

+2

」但這真的是最好的方法嗎?「是。 –

+0

好的。所以Box可能應該有一個傳遞大理石處理方法的超類? (如果我定義其他包含對象,例如Bin,則我可以保留DRY。) –

+0

保持含糊不清。 'class MarbleContainingObject' :) –

回答

1
class Marble(object): 
    def __init__(self,color=None): 
     self.color=color # I'm assuming this is necessary, 
         # just because "colored marbles in 
         # a box" is so typical 
    def __repr__(self): 
     return "Marble({})".format(self.color) 

class Box(object): 
    def __init__(self,name=None,marbles=None): 
     self.name = name 
     if marbles is None: 
      marbles = list() 
     self.marbles = marbles 
    def addMarble(self,color=None): 
     self.marbles.append(Marble(color)) 
    def giveMarble(self,other): 
     # import random 
     index = random.randint(0,len(self.marbles)-1) 
     try: 
      other.marbles.append(self.marbles.pop(index)) 
     except AttributeError: 
      raise NotImplementedError("Can't currently pass marbles to an " 
             "object without a marbles list") 
    def __str__(self): 
     return '\n'.join([str(marble) for marble in self.marbles]) 

a = Box() 
b = Box() 
for _ in range(10): a.addMarble() 
print(a) 
# Marble(None) 
# Marble(None) 
# Marble(None) 
# Marble(None) 
# Marble(None) 
# Marble(None) 
# Marble(None) 
# Marble(None) 
# Marble(None) 
# Marble(None) 
a.giveMarble(b) 
print(b) 
# Marble(None) 
0

是的,composition意味着所有者對象(盒)負責創建和銷燬擁有的對象(大理石)。 「