组合模式

定义:

  将对象组合成树形结构以表示部分-整体的层次结构,使得用户对单个对象和组合对象的使用具有一致性

 

场景:

   场景一:表示对象的部分-整体结构时

   场景二:从一个整体中能够独立出部分模块或功能的场景

   例子: iOS中UIView为根节点,继承UIView的UITableView,UILabel等为具体子节点...

 

角色划分: 

 

  3个核心角色

 

    角色一:抽象根节点(Component

 

    角色二:具体子节点(Composite

 

    角色三:叶子节点(太监节点->没有儿子)(Leaf)

 

 

 

 

  iOS UI架构设计->组合模式灵活运用

 

  抽象根节点->UIView

 

  具体子节点->UITableViewUIImageView…

 

  iOS开发太监View(可能会有)

 

  注意:容器存储这些儿子,这是组合模式种核心特点

 

 

 

  整体->UIView

 

  部分->UIView子类

 

  UIView有层次结构

 

  UIViewUITableView基本使用类似的

  

 

  叶子节点场景:只允许使用,不允许继承

 

  整体和部分是相对的(不是绝对的)->参照物

 

 

代码:    

  ComonentProtocol

import Foundation

protocol ComponentProtocol {
    
    var name: String { get }
    var componets: [ComponentProtocol] { get }
    
    func execute ()
}

  

Composite: 具体子节点

import UIKit

class Composite: ComponentProtocol {
    
    var name: String
    var componets: [ComponentProtocol]
    
    init(name: String) {
        self.name = name
        self.componets = [ComponentProtocol]()
        
    }
    
    func execute() {
        print("execute something")
    }
    

    //增加
    func addChild(child: ComponentProtocol) {
        self.componets.append(child)
    }
    
    //删除
    func removeChild(child: ComponentProtocol) {
        for index in 0..<self.componets.count {
            if self.componets[index].name == child.name {
                self.componets.remove(at: index)
            }
        }
    }
    
    //得到
    func getChild(index: Int) -> ComponentProtocol {
        return self.componets[index]
    }
    
    //清空
    func clearAll() {
        self.componets.removeAll()
    }

}

  叶子节点: Leaf

  

import UIKit

final class Leaf: ComponentProtocol {
    
    var name: String
    var componets: [ComponentProtocol]
    
    init(name: String) {
        self.name = name
        self.componets = [ComponentProtocol]()
    }
    
    func execute() {
        print("execute something")
    }
    
    //增加
    func addChild(child: ComponentProtocol) {
        print("发生错误,叶子节点没有子节点")
    }
    
    //删除
    func removeChild(child: ComponentProtocol) {
        print("发生错误,叶子节点没有子节点")
    }
    
    //得到
    func getChild(index: Int) -> ComponentProtocol {
        print("发生错误,叶子节点没有子节点")
        return self.componets[index]
    }
    
    //清空
    func clearAll() {
        print("发生错误,叶子节点没有子节点")
    }
    


}

  使用:

    

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let james = Composite(name: "James")
        let kobe = Composite(name: "Kobe")
        
        james.addChild(child: kobe)
        
        let leaf = Leaf(name: "Curry")
        james.addChild(child: leaf)
    }


}

    

  

 

原文地址:https://www.cnblogs.com/jiefangzhe/p/10123336.html