Builderパターン(3) Builderでオブジェクトの妥当性を保証する

Rubyによるデザインパターン』(ラス・オルセン著 ピアソン・エデュケーション刊)の例をPythonに変換して書いています。目次


Builderはオブジェクト生成を簡単にするだけでなく、より安全にする事ができます。つまり、実際にオブジェクトを返す前に、オブジェクトをチェックするのです。

前回のコンピュータの例で言えば、メモリサイズが小さすぎない等のチェックを、computerメソッドの中で行います。

def computer(self):
    assert self._computer.motherboard.memory_size >= 256, \
           "not enough memory."
    
    assert len(self._computer.drives) <= 4, "too meny drives."
    
    for drive in self._computer.drives:
        if drive.type=="harddisk":break
    else:
        raise False, "No harddisk."
    
    return self._computer