using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace Walter.K.Wang.Abstract
...{
public abstract class ContinentFactory
...{
public abstract Herbivore CreateHerbivore();
public abstract Carnivore CreateCarnivore();
}
public class AfricaFactory : ContinentFactory
...{
public override Herbivore CreateHerbivore()
...{
return new Wildebeest();
}
public override Carnivore CreateCarnivore()
...{
return new Lion();
}
}
public class AmericaFactory : ContinentFactory
...{
public override Herbivore CreateHerbivore()
...{
return new Bison();
}
public override Carnivore CreateCarnivore()
...{
return new Wolf();
}
}
public abstract class Herbivore
...{
}
public abstract class Carnivore
...{
public abstract void Eat(Herbivore h);
}
class Wildebeest : Herbivore
...{
}
class Lion : Carnivore
...{
public override void Eat(Herbivore h)
...{
MessageBox.Show(this.GetType().Name + " eats " + h.GetType().Name, "友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
class Bison : Herbivore
...{
}
class Wolf : Carnivore
...{
public override void Eat(Herbivore h)
...{
MessageBox.Show(this.GetType().Name + " eats " + h.GetType().Name, "友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public class AnimalWorld
...{
private Herbivore herbivore;
private Carnivore carnivore;
public AnimalWorld(ContinentFactory factory)
...{
carnivore = factory.CreateCarnivore();
herbivore = factory.CreateHerbivore();
}
public void RunFoodChain()
...{
carnivore.Eat(herbivore);
}
}
}
private void 抽象工廠ToolStripMenuItem_Click(object sender, EventArgs e)
...{
ContinentFactory africa = new AfricaFactory();
AnimalWorld world = new AnimalWorld(africa);
world.RunFoodChain();
ContinentFactory america = new AmericaFactory();
world = new AnimalWorld(america);
world.RunFoodChain();
}
本文通过C#代码示例展示了抽象工厂模式的应用,该模式提供了一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。示例中非洲和美洲工厂分别创建各自大陆特有的食草动物和食肉动物。
1731

被折叠的 条评论
为什么被折叠?



