加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

工厂模式

发布时间:2020-12-14 00:43:03 所属栏目:Linux 来源:网络整理
导读:? 1 namespace UnitTestProject1.BaseDesign 2 { 3 4 /// summary 5 /// 工厂方法模式要求:尽量使用抽象类或接口来定义就可以达到一个开闭原则 6 /// /summary 7 [TestClass] 8 public class BaseDesign 9 { 10 [TestMethod] 11 public void TestMethod1() 1

?

 1 namespace UnitTestProject1.BaseDesign
 2 {
 3 
 4     /// <summary>
 5     /// 工厂方法模式要求:尽量使用抽象类或接口来定义就可以达到一个开闭原则
 6     /// </summary>
 7     [TestClass]
 8     public class BaseDesign
 9     {
10         [TestMethod]
11         public void TestMethod1()
12         {
13             GetAnimalEat(new DogFactoryFactory());
14 
15             GetAnimalEat(new PigFactoryFactory());
16 
17             //如果再增加一个AnimalEat不会对现有代码有改动
18         }
19 
20         void GetAnimalEat(AnimalFactory fa)
21         {
22             Animal am = fa.GetAnimal();
23             am.Eat();
24         }
25     
26     }
27     public abstract class Animal
28     {
29         public abstract void Eat();
30     }
31 
32     public class Dog : Animal
33     {
34         public override void Eat()
35         {
36             Console.WriteLine("dog eat");
37         }
38     }
39 
40     public class Pig : Animal
41     {
42         public override void Eat()
43         {
44             Console.WriteLine("pig eat");
45         }
46     }
47 
48     public abstract class AnimalFactory
49     {
50         public abstract Animal GetAnimal();
51     }
52 
53     public class DogFactoryFactory : AnimalFactory
54     {
55         public override Animal GetAnimal()
56         {
57             return new Dog();
58         }
59 
60     }
61     public class PigFactoryFactory : AnimalFactory
62     {
63         public override Animal GetAnimal()
64         {
65             return new Pig();
66         }
67     }
68 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读