zoukankan      html  css  js  c++  java
  • 组合模式

    组合模式

    组合模式:允许你将对象组合成树型结构来表现“整体/部分”层次结构。组合能让客户以一致的方式处理个别对象以及对象组合。

     

    要点:

    1. 组合模式以不遵守单一责任原则换取透明性,让Client将组合和叶节点一视同仁。

    2. 在实现组合模式时,有很多设计上的折衷。要根据需求平衡透明性和安全性。

    3. 有时候系统需要遍历一个树枝构件的子构件很多次,这时候可以把遍历结果缓存起来。

    4. 组合模式的实现中,可以让子对象持有父对象的引用进行反向追溯。

     

    实现:

    clip_image002

    Component:为参加组合的对象声明一个公共接口,不管是组合还是叶节点。

    public abstract class Component 
    {
    	public void add(Component component) 
    	{
    		throw new UnsupportedOperationException();
    	}
    
    	public void remove(Component component) 
    	{
    		throw new UnsupportedOperationException();
    	}
    
    	public Component getChild(int i) 
    	{
    		throw new UnsupportedOperationException();
    	}
    
    	public void operation() 
    	{
    		throw new UnsupportedOperationException();
    	}
    }

    Leaf:在组合中表示叶节点对象,叶节点没有子节点。

    public class Leaf extends Component
    {
    	@Override
    	public void operation()
    	{
    		//your code
    	}
    }

    Composite:表示参加组合的有子对象的对象,并给出树枝构件的行为。

    public class Composite extends Component
    {
    	ArrayList<Component> components = new ArrayList<Component>();
    	
    	@Override
    	public void add(Component component)
    	{
    		components.add(component);
    	}
    	
    	@Override
    	public void remove(Component component)
    	{
    		components.remove(component);
    	}
    	
    	@Override
    	public Component getChild(int i)
    	{
    		return components.get(i);
    	}
    	
    	@Override
    	public void operation()
    	{
    		for (Component component : components)
    		{
    			component.operation();
    		}
    	}
    }
    

    适用性:

    以下情况使用Composite模式:

    1. 你想表示对象的部分-整体层次结构。

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

     

    优点:

    1. 组合模式可以很容易的增加新的构件。

    2. 使用组合模式可以使客户端变的很容易设计,因为客户端可以对组合和叶节点一视同仁。

    缺点:

    1. 使用组合模式后,控制树枝构件的类型不太容易。

    2. 用继承的方法来增加新的行为很困难。

  • 相关阅读:
    hdoj 2803 The MAX【简单规律题】
    hdoj 2579 Dating with girls(2)【三重数组标记去重】
    hdoj 1495 非常可乐【bfs隐式图】
    poj 1149 PIGS【最大流经典建图】
    poj 3281 Dining【拆点网络流】
    hdoj 3572 Task Schedule【建立超级源点超级汇点】
    hdoj 1532 Drainage Ditches【最大流模板题】
    poj 1459 Power Network【建立超级源点,超级汇点】
    hdoj 3861 The King’s Problem【强连通缩点建图&&最小路径覆盖】
    hdoj 1012 u Calculate e
  • 原文地址:https://www.cnblogs.com/god_bless_you/p/1755844.html
Copyright © 2011-2022 走看看