脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python设计模式之建造者模式实例详解

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

2021-05-17 00:33Andy冉明 Python

这篇文章主要介绍了Python设计模式之建造者模式,简单说明了建造者模式的概念、原理,并结合实例形式分析了Python定义及使用建造者模式相关操作技巧,需要的朋友可以参考下

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/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()

运行结果:

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

上面类的设计如下图:

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

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

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

原文链接:https://www.cnblogs.com/onepiece-andy/p/python-builder-pattern.html

延伸 · 阅读

精彩推荐