创造自己的群集类型----之----创建“包装”类以封装预定义集群类型
第一步:创建“包装”类以封装预定义集群类型
public class EncapsulatePredefinedCluster
{
private ArrayList students;
public EncapsulatePredefinedCluster()
{
students = new ArrayList(5);
}
/// <summary>
/// 注册新生
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public bool Enroll(Student s)
{
if (students.Contains(s) || students.Capacity == students.Count)
{
return false;
}
else
{
students.Add(s);
return true;
}
}
/// <summary>
/// 删除已注册学生
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public bool Drop(Student s)
{
if (!students.Contains(s))
{
return false;
}
else
{
students.Remove(s);
return true;
}
}
/// <summary>
/// 是否已经注册
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public bool IsEnrolled(Student s)
{
if (students.Contains(s))
{
return true;
}
else
{
return false;
}
}
public int GetTotalEnrollment()
{
return students.Count;
}
}
第二步:调用自定义群集
public class Course
{
private EncapsulatePredefinedCluster enrollStudents;
public Course()
{
enrollStudents = new EncapsulatePredefinedCluster();
}
public bool Enroll(Student s)
{
return enrollStudents.Enroll(s);
}
public bool Drop(Student s)
{
return enrollStudents.Drop(s);
}
public bool IsEnrolled(Student s)
{
return enrollStudents.IsEnrolled(s);
}
public int GetTotalEnrolledStudents()
{
return enrollStudents.GetTotalEnrollment();
}
}
这样做有什么好处呢:
1、使得拥有我们可以修改内部实现代码的灵活性,而不至于破坏用到该群集类型的客户端代码
2、如果打算ArrayList外的其他预定义群集类型,因我们声明的Students的属性时private,所以只要不修改现有公共方法,我们可以自由地做这样的转换。