设计模式 您所在的位置:网站首页 类图的作用 设计模式

设计模式

2023-04-10 16:26| 来源: 网络整理| 查看: 265

1、定义

在不改变原有对象的基础之上,将功能附加到对象上。提供了比继承更有弹性的替代方案(扩展原有对象功能)

2、作用

降低创建复杂对象的复杂度

隔离了创建对象的构建过程以及表示

3、UML类图

Component(抽象构件):叶子构件与容器构件共同继承的父类或者是共同实现的接口,该角色中包含所有子类共有方法的声明和实现,在抽象构件中定义了管理子构件的方法,新增构件、删除构件、获取构件。

Leaf(叶子构件):表示叶子节点,没有子节点,对于继承父类的管理子节点的方法以抛出异常的方式处理。

Composite(容器构件):表示容器节点,包含子节点,子节点可以是容器节点也可以是叶子节点,其提供一个集合来对子节点进行维护,以迭代的方式对子节点进行处理。

4、实例

(1)、Component类

public abstract class Component {// 增加一个叶子构件或树枝构件public abstract void add(Component component);// 删除一个叶子构件或树枝构件public abstract void remove(Component component);// 获得分支下的所有叶子构件和树枝构件public abstract List getChildren();// 编写业务逻辑public void operation() {} }

(2)、Composite类

public class Composite extends Component {// 构件容器private ArrayList componentArrayList = new ArrayList();// 增加一个叶子构件或树枝构件public void add(Component component) {this.componentArrayList.add(component);}// 删除一个叶子构件或树枝构件public void remove(Component component) {this.componentArrayList.remove(component);}// 获得分支下的所有叶子构件和树枝构件public List getChildren() {return this.componentArrayList;} }

(3)、Leaf类

public class Leaf extends Component {public void add(Component component) {// 空实现}public void remove(Component component) {// 空实现}public List getChildren() {return null;// 空实现} }

(4)、Client类

public class Client {public static void main(String[] args) {// 创建一个根节点Composite root = new Composite();root.operation();// 创建一个树枝构件Composite branch = new Composite();// 创建一个叶子节点Leaf leaf = new Leaf();// 建立整体root.add(branch);branch.add(leaf);}// 通过递归遍历树public static void showTree(Component root) {for (Component c : root.getChildren()) {if (c instanceof Leaf) { // 叶子节点c.operation();} else { // 树枝节点showTree(c);}}} } 5、适用性

表示对象的部分-整体层次结构

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

6、优点

(1)、统一了组合对象和叶子对象。     

(2)、简化了客户端调用,无须区分操作的是组合对象还是叶子对象。     

(3)、更容易扩展,有了Component的约束,新定义的Composite或Leaf子类能够很容易地与已有的结构一起工作。

7、缺点

很难限制组合中的组件类型

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有