工厂方法模式(Factory Method Pattern):定义一个用于创建对象的接口,让子类决定将哪一个类实例化。工厂方法模式让一个类的实例化延迟到其子类。工厂方法模式又简称为工厂模式(Factory Pattern),又可称作虚拟构造器模式(Virtual Constructor Pattern)或多态工厂模式(Polymorphic Factory Pattern)。
模式角色与结构:
工厂方法模式是类的创建模式,其用意是定义一个创建产品对象的接口,将实际创建工作推迟到子类中。
示例代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharp.DesignPattern.FactoryMethodPattern { class Program { static void Main(string[] args) { ICreator footballCreator = new FootballCreator(); // build factory ICreator baseketballCreator = new BaseketballCreator(); // build factory IAthlete footballAthlete = footballCreator.Create(); // build product IAthlete basketballAthlete = baseketballCreator.Create(); // build product footballAthlete.Run(); footballAthlete.Jump(); basketballAthlete.Run(); basketballAthlete.Jump(); Console.ReadLine(); } } // Product interface IAthlete { void Run(); void Jump(); } class FootballAthlete : IAthlete { public void Run() { Console.WriteLine("FootballAthlete Run..."); } public void Jump() { Console.WriteLine("FootballAthlete Jump..."); } } class BaseketballAthlete : IAthlete { public void Run() { Console.WriteLine("BaseketballAthlete Run..."); } public void Jump() { Console.WriteLine("BaseketballAthlete Jump..."); } } // Factory interface ICreator { IAthlete Create(); } // Concrete Factory class BaseketballCreator : ICreator { public IAthlete Create() { return new BaseketballAthlete(); } } // Concrete Factory class FootballCreator : ICreator { public IAthlete Create() { return new FootballAthlete(); } } }