Python设计模式之建造者模式实例详解

yipeiwu_com6年前Python基础

本文实例讲述了Python设计模式之建造者模式。分享给大家供大家参考,具体如下:

建造者模式(Builder Pattern):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示

下面是一个建造者模式的demo

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
大话设计模式
设计模式——建造者模式
建造者模式(Builder):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以常见不同的表示
特性: 指挥者(Director) 指挥 建造者(Builder) 建造 Product
"""
import abc
class Builder(object):
  __metaclass__ = abc.ABCMeta
  @abc.abstractmethod
  def create_header(self):
    pass
  @abc.abstractmethod
  def create_body(self):
    pass
  @abc.abstractmethod
  def create_hand(self):
    pass
  @abc.abstractmethod
  def create_foot(self):
    pass
class Thin(Builder):
  def create_header(self):
    print '瘦子的头'
  def create_body(self):
    print '瘦子的身体'
  def create_hand(self):
    print '瘦子的手'
  def create_foot(self):
    print '瘦子的脚'
class Fat(Builder):
  def create_header(self):
    print '胖子的头'
  def create_body(self):
    print '胖子的身体'
  def create_hand(self):
    print '胖子的手'
  def create_foot(self):
    print '胖子的脚'
class Director(object):
  def __init__(self, person):
    self.person = person
  def create_preson(self):
    self.person.create_header()
    self.person.create_body()
    self.person.create_hand()
    self.person.create_foot()
if __name__=="__main__":
  thin = Thin()
  fat = Fat()
  director_thin = Director(thin)
  director_fat = Director(fat)
  director_thin.create_preson()
  director_fat.create_preson()

运行结果:

瘦子的头
瘦子的身体
瘦子的手
瘦子的脚
胖子的头
胖子的身体
胖子的手
胖子的脚

上面类的设计如下图:

指挥者Director 调用建造者Builder的对象 具体的建造过程是在Builder的子类中实现的

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python 分发包中添加额外文件的方法

在制作一个 Python 分发包时经常需要把一些文件添加到包中。最常见的例子是你希望通过  pip install 命令安装 Python 包时会在  /etc/ 等...

11月编程语言排行榜 Python逆袭C#上升到第4

11月编程语言排行榜 Python逆袭C#上升到第4

TIOBE 11 月编程语言排行榜,Python 逆袭C# 曾经有一段时间,脚本语言因其易于编写和易于运行的特性,被预测在未来将发展强大。因此,Perl,Python,PHP 和 Rub...

selenium2.0中常用的python函数汇总

本文总结分析了selenium2.0中常用的python函数。分享给大家供大家参考,具体如下: 新建实例driver = webdriver.Firefox() 此处定位均使用的百度首...

使用Python实现正态分布、正态分布采样

使用Python实现正态分布、正态分布采样

多元正态分布(多元高斯分布) 直接从多元正态分布讲起。多元正态分布公式如下: 这就是多元正态分布的定义,均值好理解,就是高斯分布的概率分布值最大的位置,进行采样时也就是采样的中心点。而...

python数组循环处理方法

简介 本文主要介绍python数组循环语法。主要方式有元素遍历,索引遍历,enumerate, zip, list内部等。 普通循环 list1 = ['item1', 'item2...