1 Star 0 Fork 0

juniperwu/JavaPattern

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
Test.java 2.11 KB
Copy Edit Raw Blame History
wujf authored 2016-09-15 23:54 +08:00 . inti by wujf
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));
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/mygit2008/JavaPattern.git
git@gitee.com:mygit2008/JavaPattern.git
mygit2008
JavaPattern
JavaPattern
master

Search