1.工厂方法模式(Factory Method)
定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到子类
例子
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 工厂方法模式 { class Program { static void Main(string[] args) { IFartory factory = new UndergraduateFartory(); LeiFeng student = factory.CreatLeiFeng(); student.Sweep(); student.Wash(); student.BuyRice(); Console.Read(); } } #region- 雷锋类 - class LeiFeng { public void Sweep() { Console.Write("扫地"); } public void Wash() { Console.Write("洗衣"); } public void BuyRice() { Console.Write("买米"); } } #endregion #region- 学雷锋的大学生类 - class Undergraduate:LeiFeng { } #endregion #region- 社区志愿者类 - class Volunteer:LeiFeng { } #endregion #region- 雷锋工厂 - interface IFartory { LeiFeng CreatLeiFeng(); } #endregion #region- 学雷锋的大学生工厂 - class UndergraduateFartory:IFartory { public LeiFeng CreatLeiFeng() { return new Undergraduate(); } } #endregion #region- 社区志愿者工厂 - class VolunteerFartory:IFartory { public LeiFeng CreatLeiFeng() { return new Volunteer(); } } #endregion }
运行结果: