namespace _09_Composite
{
public interface IBox
{
void process();
}
public class SingleBox : IBox
{
public void process()
{
}
}
public class ContainerBox : IBox
{
public void process()
{
}
public ArrayList getBoxes()
{
return new ArrayList();
}
}
/// <summary>
/// 客户代码
/// </summary>
internal class Program
{
//static void Main(string[] args)
//{
// IBox box = new SingleBox();
// //客户代码与对象内部结构发生了耦合
// if (box is ContainerBox)
// {
// box.process();
// ArrayList list = ((ContainerBox)box).getBoxes();
// }
// else if (box is SingleBox)
// {
// box.process();
// }
//}
}
}
namespace _09_Composite_2
{
public interface IBox
{
void Process();
void Add(IBox box);
void Remove(IBox box);
}
public class SingleBox : IBox
{
public void Add(IBox box)
{
}
public void Remove(IBox box)
{
}
public void Process()
{
}
}
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 void Process()
{
//1.Do process for myself
//2.Do process for the box in the list
if (list != null)
{
foreach (IBox box in list)
{
box.Process();
}
}
}
public IList getBoxes()
{
return list;
}
}
/// <summary>
/// 客户代码
/// </summary>
internal class Program
{
static void Main(string[] args)
{
IBox box = null;
box = new SingleBox();
box = new ContainerBox();
//客户代码与抽象接口发生了耦合
box.Process();
}
}
}
08.组合模式
最新推荐文章于 2025-04-06 23:20:56 发布