zoukankan      html  css  js  c++  java
  • 建造者模式

    建造者模式,是创建型模式中的第三种模式,一般的开发过程中用的比较少。所以只做简单的介绍。

    根据书上的介绍,建造者模式通常用于补充工厂模式的不足,尤其是在如下场景中:

    要求一个对象有不同的表现,并且希望将对象的构造与表现解耦
    要求在某个时间点创建对象,但在稍后的时间点再访问

    看起来是很难理解,其实最常用的一个场景就是操作数据库的 orm。回想一下,orm 中一个很重要的概念:延迟加载,
    其实就是建造者模式最常见的应用。
    在一开始将 orm 对象构造出来,但并不实际查询数据,而是在用到具体数据的时候才向数据库进行查询。
    并且会根据不同的对象,向不同的表进行查询。

    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 '
    '.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):
                return Pizza(self)
    
    if __name__ == '__main__':
        pizza = Pizza.PizzaBuilder().add_garlic().add_extra_cheese().build()
        print(pizza)
    

      这个代码其实是建造者模式的一种变体,实现了链式调用。其实这种所谓的链式调用,也并不是什么神奇的事情,只是在建造者类的每一个方法里返回其本身——return self——罢了。

  • 相关阅读:
    【原】PHP从入门到精通2小时【图文并茂】
    VMware虚拟机扩容
    linux修改固定IP
    According to TLD or attribute directive in tag file, attribute items does not accept any expressions
    eclipse juno 怎么安装maven
    MySQL的ROUND函数
    GitHub如何删除一个代码仓库
    win7企业版激活
    git-中文乱码
    Eclipse各个版本及其对应代号、下载地址列表【转】
  • 原文地址:https://www.cnblogs.com/wumingxiaoyao/p/8478558.html
Copyright © 2011-2022 走看看