简单工厂 模式根据提供给它的数据返回几个可能类中的一个实例.通常返回的类有共同的基类和方法,但执行不同的操作,而且可以根据数据的做响应优化.
using
System;
namespace
NameFactory
...
{ /**/ /// <summary> /// Summary description for NameFactory. /// </summary> public class NameFactory ... { public NameFactory() ... {} public Namer getName( string name) ... { int i = name.IndexOf ( " , " ); if (i > 0 ) return new LastFirst (name); else return new FirstFirst (name); } } }
using
System;
namespace
NameFactory
...
{ /**/ /// <summary> /// Summary description for FirstFirst. /// </summary> public class FirstFirst : Namer ... { public FirstFirst( string name) ... { int i = name.IndexOf ( " " ); if (i > 0 ) ... { frName = name.Substring ( 0 , i).Trim (); lName = name.Substring (i + 1 ).Trim (); } else ... { lName = name; frName = "" ; } } } }
using
System;
namespace
NameFactory
...
{ /**/ /// <summary> /// Summary description for LastFirst. /// </summary> public class LastFirst : Namer ... { public LastFirst( string name) ... { int i = name.IndexOf ( " , " ); if (i > 0 ) ... { lName = name.Substring ( 0 , i); frName = name.Substring (i + 1 ).Trim (); } else ... { lName = name; frName = "" ; } } } }
很显然,NameFactory 就是所谓的决策类,将根据传入条件的不同,返回不同的实例.即 :
或则返回LastFirst,或则FirstFirst ,但它们有一个共同的特点,都派生自Namer,拥有共同的属性和操作.