不同物件卻須集合在一起控制.
例如:資料夾裡面除了放圖片以外,還可以放excel,電影檔,跟圖片,而在資料夾內,又可以放入新的物件,或是移除等動作
實作方面就需要用到泛型與物件屬性,這是.Net Framework 3.0含以上的版本才有
使用方式:
namespace CompositePattern {以上面的例子來說:
// The Interface
public interface IComponent <T>
{
void Add(IComponent <T> c);
IComponent <T> Remove(T s);
IComponent <T> Find(T s);
T Name {get; set;}
}
// The Component
public class Component <T> : IComponent <T>
{
public T Name {get; set;}
public Component (T name)
{
Name = name;
}
public void Add(IComponent <T> c)
{
Console.WriteLine("Cannot add to an item");
}
public IComponent <T> Remove(T s)
{
Console.WriteLine("Cannot remove directly");
return this;
}
public IComponent <T> Find (T s)
{
if (s.Equals(Name))
return this;
else
return null;
}
}
// The Composite
public class Composite <T> : IComponent <T>
{
List<IComponent <T>> list;
public T Name {get; set;}
public Composite (T name)
{
Name = name;
list = new List <IComponent <T>> ( );
}
public void Add(IComponent <T> c)
{
list.Add(c);
}
IComponent <T> holder=null;
// Finds the item from a particular point in the structure// and returns the composite from which it was removed// If not found, return the point as given
public IComponent <T> Remove(T s)
{
holder = this;
IComponent <T> p = holder.Find(s);
if (holder!=null)
{
return holder;
}
else
return this;
(holder as Composite<T>).list.Remove(p);
}
// Recursively looks for an item// Returns its reference or else null
public IComponent <T> Find (T s)
{
holder = this;
if (Name.Equals(s)) return this;
IComponent <T> found=null;
foreach (IComponent <T> c in list)
{
found = c.Find(s);
if (found!=null)
break;
}return found;
}
}
}
使用IComponent <T> 泛型介面,提供任一型別皆可繼承
實作Component <T>物件,透過繼承IComponent <T>泛型介面來實作並提供物件本身可供外部存取,注意的是(物件本身不對自己做Add(),Remove()動作,是由外部容器提供)
實作Composite <T>物件,透過繼承IComponent <T>泛型介面來實作並提供物件本身可供外部存取,注意的是(物件本身對Component <T>做Add(),Remove()動作)
而外部存取時,使用方式如下
IComponent <string> album = new Composite<string>("Album");參考書籍c#3.0 design pattern
Image img1 = new Image();
album.Add(new Component<Image>(img1 ));
album.Find(img1 );
沒有留言:
張貼留言