composit模式
原始耦合度较高的操作方式:
old
using System.Collections;
public interface IBox
{
void process();
}
public class SingleBox : IBox
{
public void process() { }
}
public class ContainerBox : IBox
{
public void process() { }
public ArrayList getBoxes()
{
//..
}
}
//客户代码与对象内部结构发生耦合
class App
{
public static void Main()
{
IBox box = Factory.GetBox();
//客户代码与对象内部发生耦合
if(box is ContainerBox)
{
box.process();
ArrayList list = ((ContainerBox)box).getBoxes();
//..//将面临较为复杂的递归处理
}
else if (box is SingleBox)
{
box.process();
}
}
}
using System.Collections;
public interface IBox
{
void process();
}
public class SingleBox : IBox
{
public void process() { }
}
public class ContainerBox : IBox
{
public void process() { }
public ArrayList getBoxes()
{
//..
}
}
//客户代码与对象内部结构发生耦合
class App
{
public static void Main()
{
IBox box = Factory.GetBox();
//客户代码与对象内部发生耦合
if(box is ContainerBox)
{
box.process();
ArrayList list = ((ContainerBox)box).getBoxes();
//..//将面临较为复杂的递归处理
}
else if (box is SingleBox)
{
box.process();
}
}
}
用composit方式操作:
composit
using System.Collections;
public interface IBox
{
void process();
void Add(IBox box);
void Remove(IBox box);
}
public class SingleBox : IBox
{
public void process()
{
//Do process for myself
//..
}
public void Add(IBox box)
{
throw UnsupportedException();
}
public void Remove(IBox box)
{
throw UnsupportedException();
}
}
public class ContainerBox : IBox
{
ArrayList list = null;
public void Add(IBox box)
{
if (list == null)
{
list = new ArrayList();
}
list.Add(box);
}
public void Remove(IBox box)
{
if(list == null)
{
throw new Exception();
}
list.Remove(box);
}
public IList GetBoxes()
{
return list;
}
public void process()
{
//1.Do Something for myself
//
//2.Do process for the boxes in the list
if (list != null)
{
foreach (IBox box in list)
{
box.process();
}
}
}
}
class App
{
public static void Main()
{
IBox box = Factory.GetBox();
//客户代码与抽象借口进行耦合
box.process();
box.Add(Factory.GetBox());
}
}
using System.Collections;
public interface IBox
{
void process();
void Add(IBox box);
void Remove(IBox box);
}
public class SingleBox : IBox
{
public void process()
{
//Do process for myself
//..
}
public void Add(IBox box)
{
throw UnsupportedException();
}
public void Remove(IBox box)
{
throw UnsupportedException();
}
}
public class ContainerBox : IBox
{
ArrayList list = null;
public void Add(IBox box)
{
if (list == null)
{
list = new ArrayList();
}
list.Add(box);
}
public void Remove(IBox box)
{
if(list == null)
{
throw new Exception();
}
list.Remove(box);
}
public IList GetBoxes()
{
return list;
}
public void process()
{
//1.Do Something for myself
//
//2.Do process for the boxes in the list
if (list != null)
{
foreach (IBox box in list)
{
box.process();
}
}
}
}
class App
{
public static void Main()
{
IBox box = Factory.GetBox();
//客户代码与抽象借口进行耦合
box.process();
box.Add(Factory.GetBox());
}
}