【软考学习】设计模式——组合模式
来源:互联网 发布:意识与人工智能 编辑:程序博客网 时间:2024/06/05 18:40
【背景】
设计模式是非常重要的一块知识,每个设计模式都值得深入了解和学习。
【内容】
结构型设计模式总结:
合成(组合)设计模式总结:
一、定义:将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。二、UML结构图:
三、代码实现:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 组合模式{ class Program { static void Main(string[] args) { Component root = new Composite("root"); root.Add(new Leaf("Leaf A")); root.Add(new Leaf("Leaf B")); Composite comp = new Composite("Composite X"); comp.Add(new Leaf("Leaf XA")); comp.Add(new Leaf("Leaf XB")); root.Add(comp); Composite comp2 = new Composite("Composite XY"); comp.Add(new Leaf("Leaf XYA")); comp.Add(new Leaf("Leaf XYB")); comp.Add(comp2); root.Add(new Leaf("Leaf C")); Leaf leaf = new Leaf("Leaf D"); root.Add(leaf); root.Remove(leaf); root.Display(1); Console.Read(); } } abstract class Component { protected string name; public Component(string name) { this.name = name; } public abstract void Add(Component c); public abstract void Remove(Component c); public abstract void Display(int depth); } class Leaf : Component { public Leaf(string name) : base(name) { } public override void Add(Component c) { Console.WriteLine("Cannot add to a leaf"); } public override void Remove(Component c) { Console.WriteLine("Cannot remove from a leaf"); } public override void Display(int depth) { Console.WriteLine(new String('-', depth) + name); } } class Composite : Component { private List<Component> children = new List<Component>(); public Composite(string name) : base(name) { } public override void Add(Component c) { children.Add(c); } public override void Remove(Component c) { children.Remove(c); } public override void Display(int depth) { Console.WriteLine(new string('-',depth)+name); foreach (Component component in children ) { component.Display(depth + 2); } } }}
阅读全文
0 0
- 【软考学习】设计模式——组合模式
- 【软考学习】设计模式——单例模式
- 【软考学习】设计模式——建造者模式
- 【软考学习】设计模式——原型模式
- 【软考学习】设计模式——适配器模式
- 【软考学习】设计模式——装饰模式
- 【软考学习】设计模式——代理模式
- 【软考总结】——组合模式
- 设计模式学习笔记—组合模式
- 【软考学习】设计模式——宏观总结
- 【软考学习】设计模式——工厂方法
- 【软考学习】设计模式——抽象工厂
- 设计模式—组合模式
- 设计模式—组合模式
- 【软考】——重温设计模式☞命令模式
- 软考设计模式——装饰模式(C++)
- 软考总结— 设计模式之状态模式
- 软考--设计模式
- pl/sql 函数之判断多个分割的数字是否在某个范围
- java虚拟机之二虚拟机内存结构
- [LeetCode] Matrix 值修改系列,例题 Surrounded Regions,Set Matrix Zeroes
- 如何作为一个优秀的程序员
- 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.
- 【软考学习】设计模式——组合模式
- 习题3.1
- CentOS下安装JDK1.7
- CSS初始之踩坑
- Jmeter安装教程+Jmeter快捷方式图标制作
- PXE+Kickstart无人值守安装
- 《阿里巴巴Java开发手册(正式版)》--MySQL规约
- C++ STL第三周笔记
- oralce字符窜转变为数组