组合模式是一种结构型模式,是一种将对象组合成树状的层次结构的模式,表示整体与部分的关系。在人口统计中,按照行政区域来统计的,省市县就是典型的树形结构。如下
namespace Designmode.Composite
{
/// <summary>
/// 计算人口的接口
/// </summary>
public interface ICount
{
/// <summary>
/// 统计人口
/// </summary>
/// <returns>总人口</returns>
int Count();
}
}
namespace Designmode.Composite
{
public class City : ICount
{
/// <summary>
/// 城市人口
/// </summary>
private int _population = 0;
/// <summary>
/// 城市名称
/// </summary>
private string _name = "";
/// <summary>
/// 构建一个城市类
/// </summary>
/// <param name="population"></param>
public City(int population, string name)
{
this._population = population;
this._name = name;
}
/// <summary>
/// 统计人口
/// </summary>
/// <returns></returns>
public int Count()
{
Console.WriteLine($"{this._name}: {this._population}");
return this._population;
}
}
}
namespace Designmode.Composite
{
/// <summary>
/// 区域,包含若干个城市
/// </summary>
public class Region : ICount
{
/// <summary>
/// 区域名称
/// </summary>
private string _name;
/// <summary>
/// 构造包含若干个城市的区域
/// </summary>
/// <param name="name">区域名称</param>
public Region(string name)
{
this._name = name;
}
/// <summary>
/// 区域包含的城市
/// </summary>
private List<ICount> _citys = new List<ICount>();
/// <summary>
/// 添加城市
/// </summary>
/// <param name="city">要添加的城市</param>
public void Add( ICount city)
{
if (city != null && !_citys.Contains(city))
{
_citys.Add(city);
}
}
/// <summary>
/// 移除城市
/// </summary>
/// <param name="city">要移除的城市</param>
public void Remove(ICount city)
{
if (_citys.Contains(city))
{
_citys.Remove(city);
}
}
/// <summary>
/// 统计区域人口
/// </summary>
/// <returns>区域人口数</returns>
public int Count()
{
int sum = 0;
foreach (var city in _citys)
{
sum += city.Count();
}
Console.WriteLine($"{this._name}: {sum}");
return sum;
}
}
}