UML類圖:
代碼示例:
[csharp]
//基類
public abstract class Animal
{
public string Name { get; set; }
public abstract void Run();
}
//子類1
public class Chicken : Animal
{
public override void Run()
{
Console.WriteLine("Chicken was running...");
}
}
//子類2
public class Dog : Animal
{
public override void Run()
{
Console.WriteLine("Dog was running...");
}
}
//工廠類
public class AnimalFactory
{
public Animal CreateAnimal(string animalType)
{
switch (animalType) //依靠字符串分類
{
case "chicken":
return new Chicken();
case "dog":
return new Dog();
default:
throw new Exception("Invalid param...");
}
}
}
//基類
public abstract class Animal
{
public string Name { get; set; }
public abstract void Run();
}
//子類1
public class Chicken : Animal
{
public override void Run()
{
Console.WriteLine("Chicken was running...");
}
}
//子類2
public class Dog : Animal
{
public override void Run()
{
Console.WriteLine("Dog was running...");
}
}
//工廠類
public class AnimalFactory
{
public Animal CreateAnimal(string animalType)
{
switch (animalType) //依靠字符串分類
{
case "chicken":
return new Chicken();
case "dog":
return new Dog();
default:
throw new Exception("Invalid param...");
}
}
}