読者です 読者をやめる 読者になる 読者になる

牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

Python でデザパタ -- ファクトリメソッド/Factory Method

Python

(Python2.7)

Factory Method

元ネタ

InstrumentFactory
class Saxophone(object):
    def __init__(self, name):
        self.name = name

    def play(self):
        return "{name} is playing the sounds".format(name=self.name)


class Trumpet(object):
    def __init__(self, name):
        self.name = name

    def play(self):
        return "{name} is playing the sounds".format(name=self.name)


class InstrumentFactory(object):
    def __init__(self, number_saxophones):
        self.instruments = []
        for num in range(number_saxophones):
            instrument = self.new_instrument("{num}".format(num=num))
            self.instruments.append(instrument)

    def ship_out(self):
        self.tmp = self.instruments
        self.instruments = []
        return self.tmp

    def new_instrument(self):
        pass


class SaxophoneFactory(InstrumentFactory):
    def new_instrument(self, name):
        return Saxophone("Saxophone" + name)


class TrumpetFactory(InstrumentFactory):
    def new_instrument(self, name):
        return Trumpet("Trumpet" + name)


if __name__ == '__main__':
    factory = SaxophoneFactory(3)
    saxophones = factory.ship_out()
    print("\n".join([saxophone.play() for saxophone in saxophones]))
    #-> Saxophone0 is playing the sounds
    #-> Saxophone1 is playing the sounds
    #-> Saxophone2 is playing the sounds

    factory = TrumpetFactory(3)
    trumpets = factory.ship_out()
    print("\n".join([trumpet.play() for trumpet in trumpets]))
    #-> Trumpet0 is playing the sounds
    #-> Trumpet1 is playing the sounds
    #-> Trumpet2 is playing the sounds