工厂模式
何为工厂模式:定义一个用于创建对象的接口,让子类去决定实例化那一个类,FactoryMethod可以使一个类的实例化延迟到其子类。
工厂模式分类
工厂模式按其形态分主要分为三类:简单工厂、工厂模式和抽象工厂模式。
简单工厂模式
简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。顾名思义工厂就是生产东西的,有原料(参数),模子(对象)就能生产出很多个具有相同功能的对象啦。
uml图
代码实现
- public class Program
- {
- static void Main(string[] args)
- {
- LeiFeng studentA = SimpleFactory.CreateLeiFeng("学雷锋的大学生");//用简单工厂创建并实例化学雷锋的大学生
- studentA.BuyRice();
- LeiFeng studentB = SimpleFactory.CreateLeiFeng("社区志愿者");//用简单工厂创建实例化社区志愿者
- studentB.BuyRice();
- }
- }
- //雷锋类,定义了一些功能
- class LeiFeng
- {
- public void Sweep(){ } //擦桌子
- public void Wash(){ } //洗衣服
- public void BuyRice(){ } //买米
- }
- //简单工厂类
- class SimpleFactory
- {
- public static LeiFeng CreateLeiFeng(string type)
- {
- LeiFeng result = null;
- switch (type) //判断选择要创建对象的类型
- {
- case "学雷锋的大学生":
- result = new UnderGraduate();
- break;
- case "社区志愿者":
- result = new UnderGraduate();
- break;
- }
- return result;
- }
- }
工厂模式:创建对象的接口,让子类去决定具体实例化的对象
- public class Program {
- static void Main(String[] args)
- {
- IFactory factory = new UndergraduateFactory(); //由接口创建新的学雷锋大学生
- LeiFeng student = factory.CreateLeifeng(); //实例化
- student.BuyRice();
- student.Sweep();
- student.Wash();
- }
- }
- //雷锋类,定义了一些功能
- class LeiFeng
- {
- public void Sweep(){ } //擦桌子
- public void Wash(){ } //洗衣服
- public void BuyRice(){ } //买米
- }
- //学雷锋的大学生
- class UnderGraduate : LeiFeng{ }
- //社区志愿者
- class Volunteer : LeiFeng{ }
- //雷锋工厂
- interface IFactory //定义一个接口,实现创建雷锋类的功能
- {
- LeiFeng CreateLeifeng();
- }
- class UndergraduateFactory : IFactory//学雷锋大学生工厂
- {
- public LeiFeng CreateLeiFeng()
- {
- return new UnderGraduate();
- }
- }
- class VolunteerFactory : IFactory//社区志愿者工厂
- {
- public LeiFeng CreateLeiFeng()
- {
- return new Volunteer();
- }
- }
本文详细介绍了工厂模式的概念及其三种形态:简单工厂、工厂模式和抽象工厂模式,并通过代码示例展示了如何使用这些模式来创建对象。
1154

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



