简单工厂模式与工厂方法模式

时间:2022-10-01 23:32:31

简单工厂模式:

     简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特殊实现。(百科)

最大的优点是包含了必要的逻辑判断,根据客户端选择条件动态实例化相关的类,对于客户端来说去除了与具体产品的依赖。但是违背了开发——封闭原则。

工厂方法模式:

    定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类

所谓的决定并不是允许子类在运行时做决定,而是指在编写创建者类时,不需知道创建的产品是哪一下,选择了哪个子类,就决定了实际创建的产品是什么。

简单工厂模式与工厂方法模式

代码:

class Program
{
static void Main(string[] args)
{
IFactory factory = new UndergraduateFactory();//大学生实现接口
LeiFeng student = factory.CreateLeiFeng();//调用雷锋方法
student.BuyRice();
student.Wash();
student.Sweep();
Console.Read();
}
}

class LeiFeng//方法;product类
{
public void Sweep()
{
Console.WriteLine("扫地");
}
public void Wash()
{
Console.WriteLine("洗衣");
}
public void BuyRice()
{
Console.WriteLine("买米");
}
//添加新方法处,简单工厂是在switch的case出添加,都是要修改原来的类
}
interface IFactory//工厂,creator
{
LeiFeng CreateLeiFeng();
}
class Undergradute:LeiFeng//具体product
{ }
class UndergraduateFactory:IFactory//具体工厂
{
public LeiFeng CreateLeiFeng()
{
return new Undergradute();
}
}
class Volunteer:LeiFeng
{ }
class VolunteerFactory:IFactory
{
public LeiFeng CreateLeiFeng()
{
return new Volunteer();
}
}
//此处添加新的工厂、产品
}

nice  to meet you简单工厂模式与工厂方法模式多多指教