c#设计模式之组合模式(composition pattern)

来源:互联网 发布:mac word 简体转繁体 编辑:程序博客网 时间:2024/04/29 03:15
using System;
using System.Collections;
/// <summary>
/// Composition pattern example.
/// </summary>
/// Interface

public interface IContent 
{
    
void Add(IContent ic);
    
void Remove(IContent ic);
    
void Display();
}


public class Leaf : IContent
{
    
private int value;
    
public void Add(IContent ic) 
    
{
    }

    
public void Remove(IContent ic) 
    
{        
    }

    
public void Display() 
    
{
        Console.WriteLine(
"Leaf" + value);
    }

    
public Leaf(int val) 
    
{
        value 
= val;
    }

}


public class  Tree : IContent
{
    
private int value;
    
private ArrayList al = null;
    
public void Add(IContent ic)
    
{
        
if (al == null
        
{
            al 
= new ArrayList();
        }

        al.Add(ic);
    }

    
public void Remove(IContent ic)
    
{
        
if (al != null)
        
{
            al.Remove(ic);
        }

    }

    
public void Display() 
    
{
        Console.WriteLine(
"Tree" + value);
        
foreach (IContent ic in al) 
        
{
            ic.Display();
        }

    }

    
public Tree(int val) 
    
{
        value 
= val;
    }

}


public class MyMain
{
    
public static void Main()
    
{
        Tree root 
=new Tree(10000);
        Tree tr1 
= new Tree(1000);
        Leaf lf1
=new Leaf(10);
        Leaf lf2 
= new Leaf(20);
        Leaf lf3 
= new Leaf(30);
        tr1.Add(lf1);
        tr1.Add(lf2);
        root.Add(tr1);
        root.Add(lf3);
        root.Display();
    }

}

 以上只是组合模式的一个简单的实现。李建忠老师说得对,要理解设计模式还是要理解为什么要这么做。 上例中有一个树类和一个叶子类。对于叶子类我们没必要计较什么,因为它是一个树的最末端,该怎么使用直接使用就是了。麻烦的是那棵树,树里面有个数祖,数祖里面放置的可能是最简单的叶子,但也有可能是一颗树枝。该怎么对树对象里面的这些数据进行处理呢?

如果是在客户端代码中直接使用(这时涉及到对数据的判断从而有分别的处理:是树还是叶子),但这时的问题就是客户端代码与类的实现之间,耦合度太大。

解决的办法就是利用一个迭代在类的内部建立一个树状结构,将实现完全封装,在客户代码中根本看不到类是怎样具体对数据进行处理的,从而到达到解耦的目的。利用《设计模式》里面的话就是:将对象组合成树状结构以表示“部分—整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。

这句话可谓精辟之至。

原创粉丝点击