UML類圖:
代碼示例:
[csharp]
//策略類
public abstract class Animal
{
public abstract void Run();
}
public class Dog : Animal
{
public override void Run()
{
Console.WriteLine("Dog was running...");
}
}
public class Cat : Animal
{
public override void Run()
{
Console.WriteLine("Cat was running...");
}
}
//Context類,維護一個Animal實例
public class AnimalContext
{
public Animal AnimalInstance { get; set; }
public AnimalContext(Animal animal)
{
this.AnimalInstance = animal;
}
}
//策略類
public abstract class Animal
{
public abstract void Run();
}
public class Dog : Animal
{
public override void Run()
{
Console.WriteLine("Dog was running...");
}
}
public class Cat : Animal
{
public override void Run()
{
Console.WriteLine("Cat was running...");
}
}
//Context類,維護一個Animal實例
public class AnimalContext
{
public Animal AnimalInstance { get; set; }
public AnimalContext(Animal animal)
{
this.AnimalInstance = animal;
}
}
策略與簡單工廠結合:
[csharp]
//策略類
public abstract class Animal
{
public abstract void Run();
}
public class Dog : Animal
{
public override void Run()
{
Console.WriteLine("Dog was running...");
}
}
public class Cat : Animal
{
public override void Run()
{
Console.WriteLine("Cat was running...");
}
}
//Context類,維護一個Animal實例
public class AnimalContext
{
public Animal AnimalInstance { get; set; }
public AnimalContext(string animalType) //工廠類與Context類合並,構造函數參數string類型
{
switch(animalType)
{
case "Dog":
this.AnimalInstance = new Dog();
break;
case "Cat":
this.AnimalInstance = new Cat();
break;
default:
this.AnimalInstance = null;
break;
}
}
}
//策略類
public abstract class Animal
{
public abstract void Run();
}
public class Dog : Animal
{
public override void Run()
{
Console.WriteLine("Dog was running...");
}
}
public class Cat : Animal
{
public override void Run()
{
Console.WriteLine("Cat was running...");
}
}
//Context類,維護一個Animal實例
public class AnimalContext
{
public Animal AnimalInstance { get; set; }
public AnimalContext(string animalType) //工廠類與Context類合並,構造函數參數string類型
{
switch(animalType)
{
case "Dog":
this.AnimalInstance = new Dog();
break;
case "Cat":
this.AnimalInstance = new Cat();
break;
default:
this.AnimalInstance = null;
break;
}
}
}