#問題→オブジェクト指向におけるFizzBuzz問題
#前回→re: オブジェクト指向におけるFizzBuzz問題
ひろえむさんのコメントにより、さらに修正。
public abstract class Animal
{
private int soundsCount = 1;
public void SetCount(int count)
{
this.soundsCount = count;
}
protected abstract string SoundsString
{
get;
}
public void Sound()
{
StringBuilder sounds = new StringBuilder();
for ( int i = 0; i < this.soundsCount; i++ )
{
sounds.Append(this.SoundsString);
}
Console.WriteLine(sounds.ToString());
}
}
public class Cat : Animal
{
protected override string SoundsString
{
get
{
return "にゃー";
}
}
}
public class Dog : Animal
{
protected override string SoundsString
{
get
{
return "わん";
}
}
}
class Program
{
static void Main(string[] args)
{
Animal animal;
animal = new Dog();
animal.Sound();
animal.SetCount(3);
animal.Sound();
animal = new Cat();
animal.Sound();
Console.Read();
}
}
せっかくなのでVB版も。
Imports System.Text
Public MustInherit Class Animal
Private soundsCount As Integer = 1
Protected MustOverride ReadOnly Property SoundsString() As String
Public Sub SetCount(ByVal count As Integer)
Me.soundsCount = count
End Sub
Public Sub Sound()
Dim sounds As New StringBuilder()
For i As Integer = 1 To Me.soundsCount
sounds.Append(Me.SoundsString())
Next i
Console.WriteLine(sounds.ToString())
End Sub
End Class
Public Class Cat
Inherits Animal
Protected Overrides ReadOnly Property SoundsString() As String
Get
Return "にゃー"
End Get
End Property
End Class
Public Class Dog
Inherits Animal
Protected Overrides ReadOnly Property SoundsString() As String
Get
Return "わん"
End Get
End Property
End Class
Public Class Program
Public Shared Sub Main(ByVal args As String())
Dim animal As Animal
animal = New Dog()
animal.Sound()
animal.SetCount(3)
animal.Sound()
animal = New Cat()
animal.Sound()
Console.Read()
End Sub
End Class