Design Pattern - Structural Patterns - Composite Pattern

来源:互联网 发布:三星网络电视看不了 编辑:程序博客网 时间:2024/06/08 00:27

2007

Section 3, Chapter 4


Composite Pattern


Concept

The Composite pattern allows you to compound different subsets of functionality into a collection and then call each subset in turn in the collection at a given point.


Use

You had a collection of objects, and each object had a particular method that you wanted to call in series.


Design

A composite allows you to call the classes with a single method and loop through the collection, calling the method on each class.


  • Component - The base class with the common functionality for all classes.
  • Leaf - the object that makes up the individual objects that exist within the collection.
  • Composite - the class that forms the collection object itself.


Both the leaf and the composite classes inherit from the component, so that whether you call the individual leaf classes or the composite class, you still call the same method(s).




Illustration




//Componentabstract class Component{private string _name;public Component(string name){_name = name;}public string Name{get{return _name;}}public abstract void Draw();public override int GetHashCode(){return _name.GetHashCode();}public override bool Equals(object obj){if (obj != null && obj is Component)return _name.Equals(((Component)obj).Name);elsereturn false;}public override string ToString(){return _name;}}//Leafclass GraphicalComponent : Component{public GraphicalComponent(string name) : base(name){}public override void Draw(){......}}//compositeclass GraphicalComposite : Component{private ArrayList _children = new ArrayList();public GraphicalComposite(string name) : base(name){}public void Add(Component child){_children.Add(child);}public void Remove(Component child){_children.Remove(child);}public Component GetChild(int index){return (Component)_children[index];}public override void Draw(){foreach(Component comp in _children)comp.Draw();}}


GraphicalComposite root = new GraphicalComposite("OuterPanel");root.Add(new GraphicalComponent("Circle"));root.Add(new GraphicalComponent("Square"));root.Add(new GraphicalComponent("Triangle"));GraphicalComposite childComposite = new GraphicalComposite("InnerPanel");childComposite.Add(new GraphicalComponent("Line"));root.Add(childComposite);


GraphicalComponent removable = new GraphicalComponent("Single Line");root.Add(removable);root.Remove(removable);


A composite class can also contain other composite classes.

You can have a two-sided relationship, which means the leaf objects know about their parent composite object.







0 0
原创粉丝点击