这是我们用得比较多的一种设计模式,也是23种标准设计模式之一,使用前面讲的简单工厂设计模式,遇到具体产品经常变换时就不太适合了,违反了开闭设计原则;怎么才能避免修改工厂类呢?工厂方法模式可以做到。
  工厂方法模式要求我们应该有一个抽象的工厂类,我们知道尽量使用抽象类或接口来定义就可以达到一个开闭原则的效果,这样我们在抽象的工厂类定义一个生产产品的方法,这个方法就是工厂方法,这也是工厂方法模式的由来,他具体的行为会有他的子类或实现类来实现。如果想生产某种产品,就定义一个新的产品,新的产品工厂类,这样就实现了不同的产品进行一个不同的创建,这样如果有信的产品,只需要添加新的工厂类,原来写好的代码不会发生变化,这种方式符合开闭原则,可扩展比较好。 

设计模式二:工厂模式

添加一个具体产品,只需要在添加一个具体产品的工厂类实现抽象工厂类,不需要修改原来的代码

设计模式二:工厂模式 

示例代码:

抽象产品类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 工厂模式
 8 {
 9     /*
10        动物抽象类
11      * 抽象产品
12      */
13     public abstract class Animal
14     {
15         public abstract void Eat();
16     }
17 }

抽象工厂类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 工厂模式
 8 {
 9     /*
10       动物抽象工厂类
11      
12      */
13     public abstract class AnimalFactory
14     {
15         public abstract Animal GetAnimal();
16 
17     }
18 }

生产狗的具体工厂类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 工厂模式
 8 {
 9     /// <summary>
10     /// 具体工厂:生成狗
11     /// </summary>
12    public class DogFactory :AnimalFactory
13     {
14 
15         public override Animal GetAnimal()
16         {
17             return new Dog();
18         }
19     }
20 }

生产企鹅的具体工厂类:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 工厂模式
 8 {
 9     /// <summary>
10     /// 具体工厂:生成企鹅
11     /// </summary>
12     public class PenguinFactory :AnimalFactory
13     {
14         public override Animal GetAnimal()
15         {
16             return new Penguin();
17         }
18     }
19 }
View Code

相关文章:

  • 2022-12-23
  • 2021-05-21
  • 2022-12-23
  • 2021-04-29
  • 2021-08-15
  • 2021-06-28
  • 2021-10-31
  • 2021-12-08
猜你喜欢
  • 2021-12-17
  • 2021-07-22
  • 2022-01-09
  • 2022-12-23
相关资源
相似解决方案