您的位置:首页 > 编程语言 > C#

C#设计模式--工厂方法模式

2017-02-17 12:08 302 查看

设计模式:

工厂方法模式(Factory Method Pattern)

介绍:简单工厂模式是要在工厂类中通过数据来做个决策,在工厂类中的多个类中实例化出来其中一个要用到的类,做运算。而工厂方法模式则是他的一个的扩展,不在工厂类中做区分从而创建对应的类,而是把这个选择决策权力交给使用类的用户决定。可扩展性比简单工厂模式要好很多

工厂方法模式类图:



工厂方法模式C#代码举例:

MobilePhone类手机类

public abstract class MobilePhone
{
public abstract void print();
}

Iphone 类 苹果手机类

public class Iphone : MobilePhone
{
public override void print()
{
Console.WriteLine("我是苹果手机!");
}
}

XiaoMI 类 小米手机类

public class XiaoMI:MobilePhone
{
public override void print()
{
Console.WriteLine("我是小米手机");
}
}

SmarTisan类 锤子手机类

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

MobilePhoneFactory 类 手机工厂类

public abstract class MobilePhoneFactory
{
public abstract MobilePhone Create();
}

IphoneFactory 类 苹果手机工厂类

public override MobilePhone Create()
{
return new Iphone();
}

XiaoMiFactory类 小米手机工厂类

public override MobilePhone Create()
{
return new XiaoMI();
}

SmarTisanFactory类 锤子手机工厂类

public override MobilePhone Create()
{
return new SmarTisan();
}

测试

(即使每次增加新的品牌,只需要增加新品牌的类,以及对应工厂即可使用,方便扩展)

class Program
{
static void Main(string[] args)
{
//创建苹果手机工厂
MobilePhoneFactory mobilePhoneFactoryIphone = new IphoneFactory();
//苹果手机工厂创建手机
MobilePhone mobilePhoneIphone = mobilePhoneFactoryIphone.Create();
//由苹果工厂创建苹果手机
mobilePhoneIphone.print();

//小米工厂生产小米手机
MobilePhoneFactory mobilePhoneFactoryXiaoMi = new XiaoMiFactory();
MobilePhone mobilePhoneXiaoMi = mobilePhoneFactoryXiaoMi.Create();
mobilePhoneXiaoMi.print();

//锤子手机工厂生产锤子手机
MobilePhoneFactory mobilePhoneFactorySmarTisan = new SmarTisanFactory();
MobilePhone mobilePhoneSmarTisan = mobilePhoneFactorySmarTisan.Create();
mobilePhoneSmarTisan.print();

Console.Read();

}
}


运行结果:



源码工程文件

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: