using System; 02. 03.namespace NameFactory 04.{ 05. /// <summary> 06. /// Summary description for FirstFirst. 07. /// </summary> 08. public class FirstFirst : Namer 09. { 10. public FirstFirst(string name) 11. { 12. int i = name.IndexOf (" "); 13. if(i > 0) { 14. frName = name.Substring (0, i).Trim (); 15. lName = name.Substring (i + 1).Trim (); 16. } 17. else { 18. lName = name; 19. frName = ""; 20. } 21. } 22. } 23.}
using System; 02. 03.namespace NameFactory 04.{ 05. /// <summary> 06. /// Summary description for LastFirst. 07. /// </summary> 08. public class LastFirst : Namer 09. { 10. public LastFirst(string name) { 11. int i = name.IndexOf (","); 12. if(i > 0) { 13. lName = name.Substring (0, i); 14. frName = name.Substring (i + 1).Trim (); 15. } 16. else { 17. lName = name; 18. frName = ""; 19. } 20. } 21. } 22.}
两个派生类中构造函数根据是不是有“,”来将名字中的姓和名分割开来,分别保存的对应的变量中。
然后我们就可以构建简单的工厂了,只需要检测逗号的存在,然后返回两个类中的一个就可以了。
using System; 02. 03.namespace NameFactory 04.{ 05. /// <summary> 06. /// Summary description for NameFactory. 07. /// </summary> 08. public class NameFactory { 09. public NameFactory() {} 10. 11. public Namer getName(string name) { 12. int i = name.IndexOf (","); 13. if(i > 0) 14. return new LastFirst (name); 15. else 16. return new FirstFirst (name); 17. } 18. } 19.}