Fetch the repository succeeded.
package com.pattern.composite;
/*
* 组合模式
* 将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。
*
* 概述:
* 组合模式是关于怎样将对象形成树形结构来表现整体和部分的层次结构的成熟模式。
* 使用组合模式,可以让用户以一致的方式处理个体对象和组合对象,
* 组合模式的关键在于无论是个体对象还是组合对象都实现了相同的接口或都是同一个抽象类的子类。
*
* 模式的结构中包括三种角色:
* 1 抽象组件(Component)
* 2 Composite节点(Composite Node)
* 3 Leaf节点(Leaf Node)
*
* 优点:
* 1 组合模式中包含有个体对象和组合对象,并形成树形结构,使用户可以方便地处理个体对象和组合对象。
* 2 组合对象和个体对象实现了相同的接口,用户一般不需区分个体对象和组合对象。
* 3 当增加新的Composite节点和Leaf节点时,用户的重要代码不需要作出修改。
*/
public class Test {
public static void main(String[] args) {
IComputerDevice comper = new MainHost("comper",0);//整台电脑
IComputerDevice keyBoard = new OtherDevice("keyBoard",100);//键盘
IComputerDevice mouse = new OtherDevice("mouse",50);//鼠标
IComputerDevice displayer = new OtherDevice("displayer",500);//显示器
IComputerDevice mainCase = new MainHost("case",300);//主机箱
IComputerDevice memory = new OtherDevice("memory",200);//内存条
IComputerDevice mainBoard = new OtherDevice("mainBoard",800);//主板
IComputerDevice power = new OtherDevice("power",500);//电源
IComputerDevice hardDisk = new OtherDevice("hardDisk",500);//硬盘
mainCase.Add(mainBoard);
mainCase.Add(memory);
mainCase.Add(power);
mainCase.Add(hardDisk);
System.out.println("主机单价:"+ CountPrice.Counter(mainCase));
comper.Add(mainCase);
comper.Add(keyBoard);
comper.Add(mouse);
comper.Add(displayer);
System.out.println("电脑总价:"+ CountPrice.Counter(comper));
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。