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

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

服务器之家 - 脚本之家 - Python - Python设计模式之桥接模式原理与用法实例分析

Python设计模式之桥接模式原理与用法实例分析

2021-05-14 00:07Andy冉明 Python

这篇文章主要介绍了Python设计模式之桥接模式原理与用法,结合具体实例形式分析了Python桥接模式的相关概念、原理、定义及使用方法,需要的朋友可以参考下

本文实例讲述了python设计模式桥接模式原理与用法。分享给大家供大家参考,具体如下:

桥接模式(bridge 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
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'andy'
"""
大话设计模式
设计模式——桥接模式
桥接模式(bridge pattern):将抽象部分与它的实现部分分离,使它们都可以独立地变化.
程序实例:手机软件的分类 和 手机品牌的分类 耦合度低 两种分类中间用一个set_handsetsoft桥接,各自的变化,不影响其他分类
"""
# 抽象手机软件类
class handsetsoft(object):
  def run(self):
    pass
#具体游戏类,游戏是手机软件,继承抽象手机软件类
class handsetgame(handsetsoft):
  def run(self):
    print "运行手机游戏"
#手机通讯录
class handsetaddresslist(handsetsoft):
  def run(self):
    print "运行通信录"
#抽象手机品牌类
class handsetbrand(object):
  def __init__(self):
    self.soft = ""
  def set_handsetsoft(self,soft):
    self.soft = soft
  def run(self):
    pass
# 手机品牌n
class handsetbrandn(handsetbrand):
  def run(self):
    self.soft.run()
# 手机品牌m
class handsetbrandm(handsetbrand):
  def run(self):
    self.soft.run()
if __name__ == "__main__":
  game = handsetgame()
  address = handsetaddresslist()
  phonen = handsetbrandn()
  phonen.set_handsetsoft(game)
  phonen.run()
  phonem = handsetbrandm()
  phonem.set_handsetsoft(address)
  phonem.run()

运行结果:

Python设计模式之桥接模式原理与用法实例分析

上面类的设计如下图

Python设计模式之桥接模式原理与用法实例分析

桥接模式的核心意图就是把类的实现独立出来,让他们各自变化。这样使每种实现的变化不会影响其他实现,从而达到应对变化的目的

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

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

延伸 · 阅读

精彩推荐