当前位置: 移动技术网 > IT编程>脚本编程>Python > Python设计模式之组合模式原理与用法实例分析

Python设计模式之组合模式原理与用法实例分析

2019年06月01日  | 移动技术网IT编程  | 我要评论

dhl快递查询,帝国唱片行,达人秀第三季总决赛

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

组合模式(composite pattern):将对象组合成成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性.

下面是一个组合模式的demo:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'andy'
"""
大话设计模式
设计模式——组合模式
组合模式(composite pattern):将对象组合成成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性.
"""
# 抽象一个组织类
class component(object):
  def __init__(self, name):
    self.name = name
  def add(self,comp):
    pass
  def remove(self,comp):
    pass
  def display(self, depth):
    pass
# 叶子节点
class leaf(component):
  def add(self,comp):
    print '不能添加下级节点'
  def remove(self,comp):
    print '不能删除下级节点'
  def display(self, depth):
    strtemp = ''
    for i in range(depth):
      strtemp += strtemp+'-'
    print strtemp+self.name
# 枝节点
class composite(component):
  def __init__(self, name):
    self.name = name
    self.children = []
  def add(self,comp):
    self.children.append(comp)
  def remove(self,comp):
    self.children.remove(comp)
  def display(self, depth):
    strtemp = ''
    for i in range(depth):
      strtemp += strtemp+'-'
    print strtemp+self.name
    for comp in self.children:
      comp.display(depth+2)
if __name__ == "__main__":
  #生成树根
  root = composite("root")
  #根上长出2个叶子
  root.add(leaf('leaf a'))
  root.add(leaf('leaf b'))
  #根上长出树枝composite x
  comp = composite("composite x")
  comp.add(leaf('leaf xa'))
  comp.add(leaf('leaf xb'))
  root.add(comp)
  #根上长出树枝composite x
  comp2 = composite("composite xy")
  #composite x长出2个叶子
  comp2.add(leaf('leaf xya'))
  comp2.add(leaf('leaf xyb'))
  root.add(comp2)
  # 根上又长出2个叶子,c和d,d没张昊,掉了
  root.add(leaf('leaf c'))
  leaf = leaf("leaf d")
  root.add(leaf)
  root.remove(leaf)
  #展示组织
  root.display(1)

运行结果如下:

上面类的设计如下图:

应用场景:

在需要体现部分与整体层次的结构时

希望用户忽略组合对象与单个对象的不同,统一的使用组合结构中的所有对象时

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网