工厂模式有三个变种:1. 简单工厂,2.工厂方法,3 抽象工厂。
主要解决问题就是对象的实例化,通过我们实例化对象,就是采用 Class1 c = new Class1(),这种方式虽简单,但是维护比较麻烦,
于是就有简单工厂,我们来看代码:
继承自同一类所有的实例化工作都集中在一个工厂类中进行,如果需要修改实例化的方式,只在这里修改即可。
public class TravelFactory { public static Travel Create(string name) { switch (name) { case "Plane": return new Plane(); case "Train": return new Train(); case "Bus": return new Bus(); default: break; } throw new Exception("There is no relative class for name"); } } public abstract class Travel { public abstract void Show(); } public class Plane : Travel { public override void Show() { Console.WriteLine("Plane for Travel"); } } public class Train : Travel { public override void Show() { Console.WriteLine("Train for Travel"); } } public class Bus : Travel { public override void Show() { Console.WriteLine("Bus for Travel"); } } class Program { static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; var plane = TravelFactory.Create("Plane"); plane.Show(); var train = TravelFactory.Create("Train"); train.Show(); var bus = TravelFactory.Create("Bus"); bus.Show(); Console.ReadKey(); } }
但是上面的代码有一个明细的缺点,就是那个swich case. 较真的程序员是不能忍受这样的代码的,于是就有了工厂方法模式,
工厂方法模式,定义了一个用于创建对象的接口,让子类来决定要实例化哪一个类,
工厂方法让类把实例化延迟到其子类。
代码如下:核心的思想就是一个类有一个对应的工厂用于实例化。
public abstract class TravelFactory { public abstract Travel Create(); } public class PlaneFactory : TravelFactory { public override Travel Create() { return new Plane(); } } public class TrainFactory : TravelFactory { public override Travel Create() { return new Train(); } } public abstract class Travel { public abstract void Show(); } public class Plane : Travel { public override void Show() { Console.WriteLine("Plane for Travel"); } } public class Train : Travel { public override void Show() { Console.WriteLine("Train for Travel"); } } class Program { static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; TravelFactory planeFactory = new PlaneFactory(); planeFactory.Create().Show(); TravelFactory trainFactory = new TrainFactory(); trainFactory.Create().Show(); Console.ReadKey(); } }