标签:cto mobile class 决定 creat isa 手机 xiaomi console
介绍:简单工厂模式是要在工厂类中通过数据来做个决策,在工厂类中的多个类中实例化出来其中一个要用到的类,做运算。而工厂方法模式则是他的一个的扩展,不在工厂类中做区分从而创建对应的类,而是把这个选择决策权力交给使用类的用户决定。可扩展性比简单工厂模式要好很多
1 public abstract class MobilePhone 2 { 3 public abstract void print(); 4 }
1 public class Iphone : MobilePhone 2 { 3 public override void print() 4 { 5 Console.WriteLine("我是苹果手机!"); 6 } 7 }
1 public class XiaoMI:MobilePhone 2 { 3 public override void print() 4 { 5 Console.WriteLine("我是小米手机"); 6 } 7 }
1 public class SmarTisan : MobilePhone 2 { 3 public override void print() 4 { 5 Console.WriteLine("我是锤子手机!"); 6 } 7 }
1 public abstract class MobilePhoneFactory 2 { 3 public abstract MobilePhone Create(); 4 }
1 public class IphoneFactory:MobilePhoneFactory 2 { 3 public override MobilePhone Create() 4 { 5 return new Iphone(); 6 } 7 }
1 public class XiaoMiFactory:MobilePhoneFactory 2 { 3 public override MobilePhone Create() 4 { 5 return new XiaoMI(); 6 } 7 }
1 public class SmarTisanFactory:MobilePhoneFactory 2 { 3 public override MobilePhone Create() 4 { 5 return new SmarTisan(); 6 } 7 }
(即使每次增加新的品牌,只需要增加新品牌的类,以及对应工厂即可使用,方便扩展)
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //创建苹果手机工厂 6 MobilePhoneFactory mobilePhoneFactoryIphone = new IphoneFactory(); 7 //苹果手机工厂创建手机 8 MobilePhone mobilePhoneIphone = mobilePhoneFactoryIphone.Create(); 9 //由苹果工厂创建苹果手机 10 mobilePhoneIphone.print(); 11 12 13 //小米工厂生产小米手机 14 MobilePhoneFactory mobilePhoneFactoryXiaoMi = new XiaoMiFactory(); 15 MobilePhone mobilePhoneXiaoMi = mobilePhoneFactoryXiaoMi.Create(); 16 mobilePhoneXiaoMi.print(); 17 18 19 //锤子手机工厂生产锤子手机 20 MobilePhoneFactory mobilePhoneFactorySmarTisan = new SmarTisanFactory(); 21 MobilePhone mobilePhoneSmarTisan = mobilePhoneFactorySmarTisan.Create(); 22 mobilePhoneSmarTisan.print(); 23 24 Console.Read(); 25 26 } 27 }
标签:cto mobile class 决定 creat isa 手机 xiaomi console
原文地址:http://www.cnblogs.com/JiYF/p/6409258.html