デザインモードII:ビルダーモード

ビルダーモード

複数の部品で構成オブジェクトを作成したい、と彼の憲法は段階的に行われる必要があります。様々なパーツが作成された場合のみ、オブジェクトは完了です。その後、必要Builderパターンを

Builderのデザインパターン:複雑なオブジェクトとその分離性能の建設プロセス、建設プロセスは、複数の異なるパフォーマンスを作成するために使用することができます。

このモードでは2人の選手があります。ビルダー司令官

さまざまなコンポーネントの複雑なオブジェクトを作成するための責任をビルダー。

司令官のコースビルダーインスタンスの制御構成。

Builderパターンとファクトリパターンの違い

1.工場パターン排他的な複数のステップを作成するために、単一ステップ、及びビルダーパターンでオブジェクトを作成し、ほとんど常に同じ導体を使用します。

工場出荷時のモードにおいては、それはすぐに良いオブジェクトが作成されて返されます;とBuilderパターンでは、必要なクライアントコードが明示的に要求した場合にのみ、司令官は、最終的なオブジェクトを返します。

実際には、Builderパターンではdjango-widgyだけ適用されて。ジャンゴ-widgy Djangoはとして使用することができ、サードパーティのエディタ、ツリーを展開しているコンテンツ管理システム(コンテンツ管理システム、CMS)。これは、HTMLページで作成されたさまざまなレイアウトで、Webページビルダーが含まれています。

Appleのモデル1.アプリケーションが構築されました

クラスタイプを設定する、このようなアプローチは、直接、単純なクラスをインスタンス化無効にすることができます

アップルの例は、ハードウェア仕様のメーカーはすべての隠ぺいは、顧客は、特定のブランドやノートブックのモデルを購入することを知っています

私たちは見ることができAppleFactory、クラスのインスタンスを、他の製造パラメータは、製造プロセスが直接インスタンス化することはできません隠れていたMacMini14クラスの
バイヤーは、内部の生産工程を気にしないので、プロセスのパラメータを

MINI14 = '1.4GHZ Mac mini'

class AppleFactory:

    class MacMini14:

        def __init__(self):
            self.memory = 4 # 单位为GB
            self.hdd = 500 # 单位为GB
            self.gpu = 'Intel HD Graphics 5000'

        def __str__(self):
            info = ('Model: {}'.format(MINI14),
                    'Memory: {}GB'.format(self.memory),
                    'Hard Disk: {}GB'.format(self.hdd),
                    'Graphics Card: {}'.format(self.gpu))
            return '\n'.join(info)

    def build_computer(self, model):
        if (model == MINI14):
            return self.MacMini14()
        else:
            print("I don't know how to build {}".format(model))

if __name__ == '__main__':
    afac = AppleFactory()
    mac_mini = afac.build_computer(MINI14)
    print(mac_mini)

名前付きパラメータを使用します

引数リストの拡張を使用します

工場のモデルとモデルビルダーの違い

  1. 複数のステップでオブジェクトを作成するために、単一のステップ、作成者モードでオブジェクトを作成し、ほとんど常に司令官を使用するには、Factoryパターン。
  2. 工場出荷時のモードでは、それはすぐに良いオブジェクトが作成されて返されます;とBuilderパターンでは、必要なクライアントコードが司令官が最終的な目標を返す明示的に要求された場合にのみ、

2.ケースII:あなたはコンピュータを作りたい、司令官として、製造業者に指示を提供

まずインスタンス化HardwareEngineer呼び出し、パラメータの受け渡し、construct_computer(self, memory, hdd, gpu)行くインスタンス化、ComputerBuilder()- >Computer()

リスト形式の実行機能

        [step for step in (self.builder.configure_momory(memory),
                           self.builder.configure_hdd(hdd),
                           self.builder.configure_gpu(gpu))]
class Computer:

    def __init__(self, serial_number):
        self.serial = serial_number
        self.memory = None  # 单位为GB
        self.hdd = None     # 单位为GB
        self.gpu = None

    def __str__(self):
        info = ('Memory: {}GB'.format(self.memory),
                'Hard Disk: {}GB'.format(self.hdd),
                'Graphics Card: {}'.format(self.gpu))
        return '\n'.join(info)


class ComputerBuilder:

    def __init__(self):
         self.computer = Computer('AG23385193')

    def configure_momory(self, amount):
        self.computer.memory = amount

    def configure_hdd(self, amount):
        self.computer.hdd = amount

    def configure_gpu(self, gpu_model):
        self.computer.gpu = gpu_model


class HardwareEngineer:

    def __init__(self):
        self.builder = None

    def construct_computer(self, memory, hdd, gpu):
        self.builder = ComputerBuilder()
        [step for step in (self.builder.configure_momory(memory),
                           self.builder.configure_hdd(hdd),
                           self.builder.configure_gpu(gpu))]


    @property
    def computer(self):
        return self.builder.computer


def main():
    engineer = HardwareEngineer()
    engineer.construct_computer(hdd=500, memory=8, gpu='GeForce GTX 650 Ti')
    computer = engineer.computer
    print(computer)

if __name__ == '__main__':
    '''
    通过HardwareEngineer(传参调用ComputerBuilder,可以使用其他类也可以) --> ComputerBuilder --> Computer(负责打印输出数据)
    '''
    main()

図から分かるように、クラスのインスタンスは、層毎に行われるが、導体たmain()、最初にインスタンス化されている場合にのみ実行されました

3.ピザを作るビルダー(ビルダー)モードを使用します

ピザを作ることにするために特定の順序を必要とします。

私たちは、最初の準備をしなければならない:成分、ソース、生地

その後、生地成分と調味料ふりかけ

異なる、異なる焼成時間の要件に応じてピザは使用される成分と生地の厚さに依存します

2つのアプリケーションビルダーがあります。

  1. マーガレットは(MargaritaBuilder)のピザを作りました
  2. 作るバターベーコンピザ(CreamyBaconBuilder)

from enum import Enum
import time

PizzaProgress = Enum('PizzaProgress', 'queued preparation baking ready')
PizzaDough = Enum('PizzaDough', 'thin thick')
PizzaSauce = Enum('PizzaSauce', 'tomato creme_fraiche')
PizzaTopping = Enum('PizzaTopping', 'mozzarella double_mozzarella bacon ham mushrooms red_onion oregano')
STEP_DELAY = 3

class Pizza:

    def __init__(self, name):
        self.name = name
        self.dough = None
        self.sauce = None
        self.topping =[]

    def __str__(self):
        return self.name

    def prepare_dough(self, dough):
        self.dough = dough
        print('preparing the {} dough of your {}...'.format(self.dough.name, self))
        time.sleep(STEP_DELAY)
        print('done with the {} dough'.format(self.dough.name))


class MargaritaBuilder:

    def __init__(self):
        self.pizza = Pizza('margarita')
        self.progress = PizzaProgress.queued
        self.baking_time = 5

    def prepare_dough(self):
        self.progress = PizzaProgress.preparation
        self.pizza.prepare_dough(PizzaDough.thin)

    def add_sauce(self):
        print('adding the tomato sauce to your margarita...')
        self.pizza.sauce = PizzaSauce.tomato
        time.sleep(STEP_DELAY)
        print('done with the tomato sauce')

    def add_topping(self):
        print('adding the topping (double mozzarella, oregano) to your margarita')
        self.pizza.topping.append([i for i in
                                   (PizzaTopping.double_mozzarella, PizzaTopping.oregano)])
        time.sleep(STEP_DELAY)
        print('done with the topping (double mozzarrella, oregano)')

    def bake(self):
        self.progress = PizzaProgress.baking
        print('baking your margarita for {} seconds'.format(self.baking_time))
        time.sleep(self.baking_time)
        self.progress = PizzaProgress.ready
        print('your margarita is ready')


class CreamyBaconBuilder:

    def __init__(self):
        self.pizza = Pizza('creamy bacon')
        self.progress = PizzaProgress.queued
        self.baking_time = 7

    def prepare_dough(self):
        self.progress = PizzaProgress.preparation
        self.pizza.prepare_dough(PizzaDough.thick)

    def add_sauce(self):
        print('adding the creme fraiche sauce to your creamy bacon')
        self.pizza.sauce = PizzaSauce.creme_fraiche
        time.sleep(STEP_DELAY)
        print('done with the creme fraiche sauce')

    def add_topping(self):
        print('adding the topping (mozzarella, bacon, ham, mushrooms, red onion, oregano) to your creamy bacon')
        self.pizza.topping.append([t for t in
                                   (PizzaTopping.mozzarella, PizzaTopping.bacon,
                                    PizzaTopping.ham, PizzaTopping.mushrooms,
                                    PizzaTopping.red_onion, PizzaTopping.oregano)])
        time.sleep(STEP_DELAY)
        print('done with the topping (mozzarella, bacon, ham, mushroom, red onion, oregano)')

    def bake(self):
        self.progress = PizzaProgress.baking
        print('baking your creamy bacon for {} second'.format(self.baking_time))
        time.sleep((self.baking_time))
        self.progress = PizzaProgress.ready
        print('your creamy bacon is ready')


class Waiter:

    def __init__(self):
        self.builder = None

    def construct_pizza(self, builder):
        self.builder = builder
        [step() for step in (builder.prepare_dough,
                             builder.add_sauce, builder.add_topping, builder.bake)]

    @property
    def pizza(self):
        return self.builder.pizza


def validata_style(builders):
    try:
        pizza_style = input('What pizza would you like, [m]argarita or [c]reamy bacon? ')
        builder = builders[pizza_style]()
        valid_input = True
    except KeyError as err:
        print('Sorry, only margarita (key m) and creamy bacon (key c) are available')
        return (False, None)
    return (True, builder)

def main():
    builders = dict(m=MargaritaBuilder, c=CreamyBaconBuilder)
    valid_input = False
    while not valid_input:
        valid_input, builder = validata_style(builders)
    print()
    waiter = Waiter()
    waiter.construct_pizza(builder)
    pizza = waiter.pizza
    print()
    print('Enjoy your {}!'.format(pizza))

if __name__ == '__main__':
    main()

4.チェーン・ビルダーメソッド呼び出し(流暢ビルダー):ピザチェーン方法

ピザクラスは、(PizzaBuilderが含まれています)

()を構築するパラメータの自己を渡して、ピザを()インスタンス化するために、パラメータビルダーピザです

class Pizza:

    def __init__(self, builder):
        self.garlic = builder.garlic
        self.extra_cheese = builder.extra_cheese

    def __str__(self):
        garlic = 'yes' if self.garlic else 'no'
        cheese = 'yes' if self.extra_cheese else 'no'
        info = ('Garlic: {}'.format(garlic), 'Extra cheese: {}'.format(cheese))
        return '\n'.join(info)

    class PizzaBuilder:

        def __init__(self):
            self.extra_cheese = False
            self.garlic = False

        def add_garlic(self):
            self.garlic = True
            return self

        def add_extra_cheese(self):
            self.extra_cheese = True
            return self

        def build(self):
            # 实例化Pizza(), 传入参数self,就是Pizza的形参builder
            return Pizza(self)

if __name__ == '__main__':
    # Pizza类中包含PizzaBuilder()
    pizza = Pizza.PizzaBuilder().add_garlic().add_extra_cheese().build()
    print(pizza)
    # a = Pizza
    # print(a)
    # b = a.PizzaBuilder()
    # print(b)
    # c = b.add_garlic().add_extra_cheese().build()
    # print(c)

おすすめ

転載: www.cnblogs.com/myt2000/p/11570037.html