-
组合模式,又叫合成模式 Composite,将对象组织到树结构中
类图:
最上方是抽象节点(树枝节点,有子节点),左下方是一个树叶节点(没有子节点),而右上方出现的是树枝节点,它含有其他的节点
根据所实现的接口区别可分为安全式和透明式
合成模式可以不提供父类的管理方法,但是必须在合适的地方提供子类的管理方法,比如:add(),remove(),getChild()
- 透明式
在抽象接口构件Component
中声明了管理子类的方法,这就导致Leaf节点也要实现这些方法,显然这是不合理的,而且这只有在运行期才能报错出来.编译是不会有问题的. - 安全式
这种就是在Composite
里声明管理子类对象的所有方法,这样客户端调用就不会有问题,因为如果是Leaf节点压根就没有add,remove
这些方法,但是这个缺点是不够透明,Composite
和Leaf
节点接口不一样
代码示例:
一个透明式的合成模式,Employee
包含管理子类的方法
/**
* FileName :Component
* Author :zengzhijun
* Date : 2018/5/23 10:16
* Description:
*/
package com.byedbl.composite;
import java.util.Enumeration;
public interface Component {
void setLeaf(boolean b);
float getSalary();
String getName();
boolean add(Employee e);
void remove(Employee e);
Enumeration elements();
Employee getChild(String s);
float getSalaries();
}
package com.byedbl.composite;
/*
* A Component with some common function implementation
* You can abstract it.
*/
import java.util.*;
public class Employee implements Component {
String name;
float salary;
Vector subordinates;
boolean isLeaf;
Employee parent = null;
//-------------------------------------------
public Employee(String _name, float _salary) {
name = _name;
salary = _salary;
subordinates = new Vector();
isLeaf = false;
}
//-------------------------------------------
public Employee(Employee _parent, String _name, float _salary) {
name = _name;
salary = _salary;
parent = _parent;
subordinates = new Vector();
isLeaf = false;
}
//-------------------------------------------
public void setLeaf(boolean b) {
isLeaf = b; //if true, do not allow children
}
//-------------------------------------------
public float getSalary() {
return salary;
}
//-------------------------------------------
public String getName() {
return name;
}
//-------------------------------------------
public boolean add(Employee e) {
if (! isLeaf) {
subordinates.addElement(e);
}
return isLeaf; //false if unsuccessful
}
//-------------------------------------------
public void remove(Employee e) {
if (! isLeaf) {
subordinates.removeElement(e);
}
}
//-------------------------------------------
public Enumeration elements() {
return subordinates.elements();
}
//-------------------------------------------
public Employee getChild(String s) {
Employee newEmp = null;
if(getName().equals(s)) {
return this;
} else {
boolean found = false;
Enumeration e = elements();
while(e.hasMoreElements() && (! found)) {
newEmp = (Employee)e.nextElement();
found = newEmp.getName().equals(s);
if (! found) {
newEmp = newEmp.getChild(s);
found =(newEmp != null);
}
}
if (found) {
return newEmp;
} else {
return null;
}
}
}
//-------------------------------------------
public float getSalaries() {
float sum = salary;
for(int i = 0; i < subordinates.size(); i++) {
sum += ((Employee)subordinates.elementAt(i)).getSalaries();
}
return sum;
}
}
构造一个树结构的Frame
package com.byedbl.composite;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.util.Enumeration;
//swing classes
public class empTree extends JxFrame
implements TreeSelectionListener
{
Employee boss, marketVP, prodVP;
Employee salesMgr, advMgr;
Employee prodMgr, shipMgr;
JScrollPane sp;
JPanel treePanel;
JTree tree;
DefaultMutableTreeNode troot;
JLabel cost;
public empTree()
{
super("Employee tree");
makeEmployees();
setGUI();
}
//--------------------------------------
private void setGUI()
{
treePanel = new JPanel();
getContentPane().add(treePanel);
treePanel.setLayout(new BorderLayout());
sp = new JScrollPane();
treePanel.add("Center", sp);
treePanel.add("South", cost = new JLabel(" "));
treePanel.setBorder(new BevelBorder(BevelBorder.RAISED));
troot = new DefaultMutableTreeNode(boss.getName());
tree= new JTree(troot);
tree.setBackground(Color.lightGray);
loadTree(boss);
/* Put the Tree in a scroller. */
sp.getViewport().add(tree);
setSize(new Dimension(200, 300));
setVisible(true);
}
//------------------------------------
public void loadTree(Employee topDog)
{
DefaultMutableTreeNode troot;
troot = new DefaultMutableTreeNode(topDog.getName());
treePanel.remove(tree);
tree= new JTree(troot);
tree.addTreeSelectionListener(this);
sp.getViewport().add(tree);
addNodes(troot, topDog);
tree.expandRow(0);
repaint();
}
//--------------------------------------
private void addNodes(DefaultMutableTreeNode pnode, Employee emp)
{
DefaultMutableTreeNode node;
Enumeration e = emp.elements();
while(e.hasMoreElements())
{
Employee newEmp = (Employee)e.nextElement();
node = new DefaultMutableTreeNode(newEmp.getName());
pnode.add(node);
addNodes(node, newEmp);
}
}
//--------------------------------------
private void makeEmployees()
{
boss = new Employee("CEO", 200000);
boss.add(marketVP = new Employee("Marketing VP", 100000));
boss.add(prodVP = new Employee("Production VP", 100000));
marketVP.add(salesMgr = new Employee("Sales Mgr", 50000));
marketVP.add(advMgr = new Employee("Advt Mgr", 50000));
for (int i=0; i<5; i++)
salesMgr .add(new Employee("Sales "+new Integer(i).toString(), 30000.0F +(float)(Math.random()-0.5)*10000));
advMgr.add(new Employee("Secy", 20000));
prodVP.add(prodMgr = new Employee("Prod Mgr", 40000));
prodVP.add(shipMgr = new Employee("Ship Mgr", 35000));
for (int i = 0; i < 4; i++)
prodMgr.add( new Employee("Manuf "+new Integer(i).toString(), 25000.0F +(float)(Math.random()-0.5)*5000));
for (int i = 0; i < 3; i++)
shipMgr.add( new Employee("ShipClrk "+new Integer(i).toString(), 20000.0F +(float)(Math.random()-0.5)*5000));
}
//--------------------------------------
public void valueChanged(TreeSelectionEvent evt)
{
TreePath path = evt.getPath();
String selectedTerm = path.getLastPathComponent().toString();
Employee emp = boss.getChild(selectedTerm);
if(emp != null)
cost.setText(new Float(emp.getSalaries()).toString());
}
//--------------------------------------
static public void main(String argv[])
{
new empTree();
}
}
package com.byedbl.composite;
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//swing classes
public class JxFrame extends JFrame
{
public JxFrame(String title)
{
super(title);
setCloseClick();
setLF();
}
private void setCloseClick()
{
//create window listener to respond to window close click
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e) {System.exit(0);}
});
}
//------------------------------------------
private void setLF()
{
// Force SwingApp to come up in the System L&F
String laf = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(laf);
}
catch (UnsupportedLookAndFeelException exc)
{System.err.println("Warning: UnsupportedLookAndFeel: " + laf);}
catch (Exception exc) {System.err.println("Error loading " + laf + ": " + exc);
}
}
}
结果: