public class RoadFactory { public static Road CreateRoad() { return new Road(); } } //调用的代码 public class Test { static void Main(string[] args) { Road road = RoadFactory.CreateRoad(); } }
//客户程序 public class Test { static void Main(string[] args) { Road road = GameObjectFactory.CreateRoad(); Building building = GameObjectFactory.CreateBuilding(); Jungle jungle = GameObjectFactory.CreateJungle(); } }
public class GameObjectFactory { public static Road CreateRoad() { return new Road(); } public static Building CreateBuilding() { return new Building(); } public static Jungle CreateJungle() { return new Jungle(); } }
public abstract class FacilitiesFactory { public abstract Road CreateRoad(); public abstract Building CreateBuilding(); public abstract Jungle CreateJungle(); }
public class ModernFacilitiesFactory:FacilitiesFactory { public override Building CreateBuilding() { return new ModernBuilding(); } public override Road CreateRoad() { return new ModernRoad(); } public override Jungle CreateJungle() { return new ModernJungle(); } }
现在App类的代码可以改成如下
1 2 3 4 5 6 7 8 9
public class App { static void Main() { GameManage g = new GameManage(new ModernFacilitiesFactory()); g.BuildGameFacilities(); g.Play(); } }