From 56483989cbc7c24672f4e45eaccbc537287556ce Mon Sep 17 00:00:00 2001 From: Alexander Zhirov Date: Sun, 21 Nov 2021 15:11:59 +0300 Subject: [PATCH] example 9 --- src/example_9/.gitignore | 15 +++++++ src/example_9/dub.json | 9 +++++ src/example_9/source/app.d | 26 ++++++++++++ src/example_9/source/stat_.d | 77 ++++++++++++++++++++++++++++++++++++ 4 files changed, 127 insertions(+) create mode 100644 src/example_9/.gitignore create mode 100644 src/example_9/dub.json create mode 100644 src/example_9/source/app.d create mode 100644 src/example_9/source/stat_.d diff --git a/src/example_9/.gitignore b/src/example_9/.gitignore new file mode 100644 index 0000000..3f2ff28 --- /dev/null +++ b/src/example_9/.gitignore @@ -0,0 +1,15 @@ +.dub +docs.json +__dummy.html +docs/ +/example_9 +example_9.so +example_9.dylib +example_9.dll +example_9.a +example_9.lib +example_9-test-* +*.exe +*.o +*.obj +*.lst diff --git a/src/example_9/dub.json b/src/example_9/dub.json new file mode 100644 index 0000000..66ac211 --- /dev/null +++ b/src/example_9/dub.json @@ -0,0 +1,9 @@ +{ + "authors": [ + "Alexander" + ], + "description": "Больше статистики. Наследование.", + "license": "proprietary", + "name": "example_9", + "targetPath": "bin" +} diff --git a/src/example_9/source/app.d b/src/example_9/source/app.d new file mode 100644 index 0000000..8d93676 --- /dev/null +++ b/src/example_9/source/app.d @@ -0,0 +1,26 @@ +import std.stdio : writeln, stdin; +import std.exception : enforce; +import stat_; + +void main(string[] args) +{ + Stat[] stats; + foreach (arg; args[1 .. $]) + { + auto newStat = cast(Stat) Object.factory("stat_." ~ arg); + enforce(newStat, "Invalid statistics function: " ~ arg); + stats ~= newStat; + } + for (double x; stdin.readf(" %s ", &x) == 1;) + { + foreach (s; stats) + { + s.accumulate(x); + } + } + foreach (s; stats) + { + s.postprocess(); + writeln(s.result()); + } +} diff --git a/src/example_9/source/stat_.d b/src/example_9/source/stat_.d new file mode 100644 index 0000000..e13fc3b --- /dev/null +++ b/src/example_9/source/stat_.d @@ -0,0 +1,77 @@ +module stat_; + +interface Stat +{ + void accumulate(double x); + void postprocess(); + double result(); +} + +class IncrementalStat : Stat +{ + protected double _result; + abstract void accumulate(double x); + void postprocess() + { + } + + double result() + { + return _result; + } +} + +class Min : IncrementalStat +{ + this() + { + _result = double.max; + } + + override void accumulate(double x) + { + if (x < _result) + { + _result = x; + } + } +} + +class Max : IncrementalStat +{ + this() + { + _result = double.min_normal; + } + + override void accumulate(double x) + { + if (x > _result) + { + _result = x; + } + } +} + +class Average : IncrementalStat +{ + private uint items = 0; + this() + { + _result = 0; + } + + override void accumulate(double x) + { + _result += x; + ++items; + } + + override void postprocess() + { + if (items) + { + _result /= items; + } + } +}