オブジェクト指向におけるFizzBuzz問題
出題者によるやんちゃな解答。
# なのでFizzBuzz問題としての模範解答でわありまっしぇん!
class Program {
static void Main() {
Animal animal;
animal = new Dog();
animal.Sound();
animal.SetCount(3);
animal.Sound();
animal = new Cat();
animal.Sound();
}
}
// 鳴くもんインタフェース
interface ISound {
void SetCount(int n);
void Sound();
}
// Animalそれ自体は鳴き方を知らず、
// 導出クラスより受け渡されるISoundに移譲する。
abstract class Animal : ISound {
private ISound sound_;
protected Animal(ISound s) { sound_ = s; }
public void SetCount(int n) { sound_.SetCount(n); }
public void Sound() { sound_.Sound(); }
}
class Dog : Animal
{ public Dog() : base(new SoundImpl("わん")) {} }
class Cat : Animal
{ public Cat() : base(new SoundImpl("にゃー")) {} }
// 鳴きますぃーん。
// おたくのにゃんこはもっと可愛く鳴くでしょう
// オリジナルのらぶりー鳴きますぃーんを作ってあげてね(はあと
class SoundImpl : ISound {
private string sound_;
private int count_ = 1;
public SoundImpl(string s) { sound_ = s; }
public void SetCount(int n) { count_ = n; }
public void Sound() {
for ( int i = 0; i < count_; ++i )
System.Console.Write(sound_);
System.Console.WriteLine();
}
}