C#设计模式--简单工厂模式

设计模式:

简单工厂模式(Simple Factory Pattern)

介绍:简单工厂模式不是Gof23种设计模式之一。但它在实际的编程中经常被用到,而且思想也非常简单,下面简单举例说明:

简单工厂模式类图:

《C#设计模式--简单工厂模式》

简单工厂模式C#代码举例:

MobilePhone(手机类)

1     public abstract class MobilePhone
2     {
3         
4         public abstract void print();
5     }

Iphone(苹果手机类)

1 public class Iphone : MobilePhone
2     {
3 
4         public override void print()
5         {
6             Console.WriteLine("我是苹果品牌!");
7         }
8     }

XiaoMI(小米手机类)

1 public class XiaoMI : MobilePhone
2     {
3         public override void print()
4         {
5             Console.WriteLine("我是小米手机");
6         }
7     }

SmarTisan(锤子手机类)

public class SmarTisan : MobilePhone
    {
        public override void print()
        {
            Console.WriteLine("我是锤子手机!");
        }
    }

MobielPhoneFactory(手机工厂类)

 1 public class MobielPhoneFactory
 2     {
 3         public static MobilePhone CreateMobilePhone(string PhoneBrand)
 4         {
 5             MobilePhone mobilePhone = null;
 6             if (PhoneBrand.Equals("苹果"))
 7             {
 8                 mobilePhone = new Iphone();
 9             }
10             else if (PhoneBrand.Equals("小米"))
11             {
12                 mobilePhone = new XiaoMI();
13             }
14             else if (PhoneBrand.Equals("锤子"))
15             {
16                 mobilePhone = new SmarTisan();
17             }
18             else
19             {
20             
21             }
22             return mobilePhone;
23         }
24         
25     }

 

测试工厂代码:

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             MobilePhone mobilephone1 = MobielPhoneFactory.CreateMobilePhone("苹果");
 6             if(mobilephone1 != null)
 7             mobilephone1.print();
 8             MobilePhone mobilephone2 = MobielPhoneFactory.CreateMobilePhone("小米");
 9             if(mobilephone2 != null)
10             mobilephone2.print();
11             MobilePhone mobilephone3 = MobielPhoneFactory.CreateMobilePhone("锤子");
12             if(mobilephone3 != null)
13             mobilephone3.print();
14             Console.Read();
15         }
16     }

运行结果:

《C#设计模式--简单工厂模式》

 

总结:如有问题欢迎留言!以上便是一个简单工厂模式!

代码工程文件下载

 

    原文作者:JiYF
    原文地址: http://www.cnblogs.com/JiYF/p/6405359.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞