public class DogSoundStrategy : ISound
{
public void Make()
{
Console.WriteLine("Bar");
}
}
public class CatSoundStrategy : ISound
{
public void Make()
{
Console.WriteLine("Meow");
}
}
这是对能发声的Animal的抽象描述:
public abstract class Animal
{
public void MakeSound(ISound sound)
{
sound.Make();
}
}
具体的动物是这样的:
public class Dog : Animal
{
}
public class Cat : Animal
{
}
然后我们可以像这样调用上面的代码:
Dog dog = new Dog();
dog.MakeSound(new DogSoundStrategy()); // there is a small chance
// that you want to change your strategy
Cat cat = new Cat();
cat.MakeSound(new CatSoundStrategy()); // there is a small chance
// that you want to change your strategy
public class SpiderManState : IState
{
public void Fly()
{
Console.WriteLine("Spiderman is flying");
}
public void Run()
{
Console.WriteLine("Spiderman is running");
}
public void Swim()
{
Console.WriteLine("Spiderman is swimming");
}
public IState SetShape()
{
return new IronManState();
}
}
IronManState会是这样的:
public class IronManState : IState
{
public void Fly()
{
Console.WriteLine("IronMan is flying");
}
public void Run()
{
Console.WriteLine("IronMan is running");
}
public void Swim()
{
Console.WriteLine("IronMan is swimming");
}
public IState SetShape()
{
return new SpiderManState();
}
}