static void Main(string[] args)
{
var shapes = new List {
new Circle(2),
new Square(5),
new Square(6)
};
var areas = new AreaCalculator(shapes);
Console.WriteLine(areas.Output());
}
运行程序,您会看到如下的输出:
Sum of the areas of provided shapes: 73.56637061435917
class AreaCalculator
{
private List _shapes;
public AreaCalculator(List shapes)
{
_shapes = shapes;
}
///
/// 计算所有形状的面积总和
///
///
public double Sum()
{
List areas = new List();
foreach (var item in _shapes)
{
if (item is Square s)
{
areas.Add(Math.Pow(s.SideLength, 2));
}
else if (item is Circle c)
{
areas.Add(Math.PI * Math.Pow(c.Radius, 2));
}
}
return areas.Sum();
}
}
并新增一个 SumCalculatorOutputter 类来专门处理输出格式的逻辑:
class SumCalculatorOutputter
{
protected AreaCalculator _calculator;
public SumCalculatorOutputter(AreaCalculator calculator)
{
_calculator = calculator;
}
public string String()
{
return $"Sum of the areas of provided shapes: {_calculator.Sum()}";
}
public string JSON()
{
var data = new { Sum = _calculator.Sum() };
return System.Text.Json.JsonSerializer.Serialize(data);
}
}
此时我们再来修改一下 Main 中的调用:
static void Main(string[] args)
{
var shapes = new List {
new Circle(2),
new Square(5),
new Square(6)
};
var areaCalculator = new AreaCalculator(shapes);
var outputer = new SumCalculatorOutputter(areaCalculator);
Console.WriteLine(outputer.JSON());
Console.WriteLine(outputer.String());
}
运行程序,输出结果如下:
{"Sum":73.56637061435917}
Sum of the areas of provided shapes: 73.56637061435917