简单工厂模式 Simple Factory Pattern
定义:专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类,属于类的创建模式,通常它根据自变量的不同返回不同的类的实例。
UML图:(先挖个坑,rose不好用了,改天补上)
简单工厂模式实际上是由一个工厂类根据传入的参量,动态决定创建出那一个产品类的实例。
该模式涉及工厂角色、抽象产品角色和具体产品角色。
1. 工厂角色(Creator):是简单工厂模式的核心,负责实现创建所有实例的内部逻辑。工厂类可以被外界直接调用,创建所需产品的对象。
2. 抽象产品角色(Product):是简单工厂模式所创建的所有对象的父类,描述所有实例共有的公共接口。
3. 具体产品角色(Concrete Product):简单工厂模式所创建的所有对象都充当这个角色的某个具体类的实例。
Example:(根据书上的自己举了个粗俗的例子,不知道合不合适)
Betty说了,做人不容易,做个好人不容易,做个健康的好人更不容易啊!要想身体好,除了锻炼身体,保持心情舒畅,每天都要摄入一定量的维生素,那就要吃水果,补充体内所需的各种维生素ABCDEFG……,当然喝点酸奶效果会更好。
比如说Betty最近喜欢吃好多水果,那每天吃一种吧
类图:
代码实现:
using System;2
namespace Design_Pattern3
{4
// 抽象水果类5
abstract class Fruit6
{7
public abstract void SendFruit();8
}9

10
//具体子类,苹果类11
class Apple : Fruit12
{13
public override void SendFruit()14
{15
//throw new Exception("The method or operation is not implemented.");16
Console.WriteLine("This apple stands for my heart!");17
}18
}19
//具体子类,香蕉类20
class Banana : Fruit21
{22
public override void SendFruit()23
{24
//throw new Exception("The method or operation is not implemented.");25
Console.WriteLine("This banana stands for my heart!");26
}27
}28
//简单工厂类29
class FruitFactory30
{31
public Fruit CreatFruit(String type)32
{33
switch (type.ToLower())34
{35
case "apple": return new Apple();36
case "banana": return new Banana();37
default: return null;38
}39
}40
}41
//某天Betty吃水果^_^42
static class Someday43
{44
/// <summary>45
/// 应用程序的主入口点。46
/// </summary>47
[STAThread]48
static void Main(String[] args)49
{50
Fruit fruit;51
FruitFactory fruitFactory = new FruitFactory();52
fruit = fruitFactory.CreatFruit("Apple");53
fruit.SendFruit();54
fruit = fruitFactory.CreatFruit("Banana");55
fruit.SendFruit();56
// Console.Read();//读取按键结束程序57

58
}59
}60
}
优势:
通过使用工厂类,外界避免了直接创建具体产品对象,仅仅消费对象就可以了。
缺陷:
工厂类中集中了所有实例的创建逻辑,当系统中具体产品类增多时,可能会出现要求工厂类根据不同条件创建不通实例的需求,影响模块延伸,对系统的维护和扩展不利。
使用条件:
1. 工厂类负责创建对象比较少;
2. 客户只知道传入工厂类的参数,对于如何创建对象不关心。


浙公网安备 33010602011771号