在合成模式的原型图中,涉及到三个角色:
1、抽象构件(Component),这是给出的一个公共接口,规定了参与组合的对象的默认行为。
2、合成构件(Composite),参加组合的有子对象的对象,并给出了合成构件的行为。
3、基本构件(Leaf),参加组合的没有子对象的对象。
合成模式根据所实现的接口的不同。分为了安全模式和透明模式,
安全模式是指在Composite构件中实现管理子类对象的方法,如Add,Remove,GetChild等方法,这样在Leaf中就无法实现这些方法,即使有实现也不能通过编译,这样就达到了代码的安全。不够透明,Composite和Leaf对象使用不同的接口
1
using System;
2
using System.Text;
3
using System.Collections;
4
5
// "Component"
6
abstract class Component
7
}
2
3
4
5
6
7
透明模式,是指在接口中给出所有管理子类的方法,在Composite和Leaf中都能实现这些方法,但是如果在Leaf类中不正确的实现了这些方法,将不能在编译中被检查出来,而在运行时报错。
1
using System;
2
using System.Text;
3
using System.Collections;
4
5
// "Component"
6
abstract class Component
7
}
2
3
4
5
6
7
以上全部是借的吕老师的代码,下面的就是我自己写的了。两点了,也来不及测试了。明天再看看。
1
using System;
2
using Systme.Collection;
3
4
abstract class Component
5
2
3
4
5