2013年10月7日 星期一

Design Pattern : Factory工廠模式 (泛型)

Design Pattern : Factory工廠模式 (泛型)

藉由使用Interface和工廠模式,可以讓工廠類別(Factory Class)去做建立物件的細節,至於使用者只要使用Factory去建立需要的物件,不需要知道物件怎麼建立的,或是細節 ~ 來降低耦合性。

底下列出三種建立Factory的方法:
     Normal Factory
     Static Factory
     Override Abstract Factory

1.  首先我們先建立一個InterfaceICar 然後實作了三個Class … Focus, Civic, V60 (這邊只列出一個)

interface ICar
{
  Color Color { get; set; }
 
String Name { get; set; }
 
void Drive();
}

class
Focus:ICar
{
  
private Color color;
  
private String name;// = typeof(Focus).Name;
  
private const String BRAND = "FORD";
  
public Focus()
   {
    
//
取得當前類別名稱
    
name = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
   }

  
public Color Color
   {
     
get { return color; }
     
set { color = value; }
   }
  
public String Name
   {
     
get { return name; }
     
set { name = value; }
   }
  
public void Drive()
   {
    
Console.WriteLine("I am driving {0} {1} ({2})", color.ToString(), name, BRAND);
   }
}

2.  Normal Factory
static class CarFactoryNormal
{
  
public static ICar Create<T>() where T:ICar
  
{
     
ICar createCar;
     
switch(typeof(T).Name.ToString())
      {
        
case "Focus":
             createCar =
new Focus();
            
break;
        
case "Civic":
             createCar =
new Civic();
            
break;
         
case "V60":
             createCar =
new V60();
            
break;
        
default:
             createCar =
null;
            
break;
      }
     
return createCar as ICar;
   }
}


使用方式:
ICar _focus = CarFactoryNormal.Create<Focus>();
_focus.Color =
Color.Silver;
_focus.Drive();


3.      Static Factory
非常簡潔明瞭的方式~~

/// <typeparam name="F">Interface</typeparam>
///
<typeparam name="T">Class</typeparam>
public static class CarFactoryStatic<F,T> where T:F, new()
{
 
public static F Create()
  {
   
return new T();
  }
}


使用方式:
ICar _focus = CarFactoryStatic<ICar, Focus>.Create();
_focus.Color =
Color.Silver;
_focus.Drive();


4.  Override Abstract Factory
利用AbstractOverride,可以建立更多客製化的Factory,比如下面會在建立ICar物件前,先顯示一段訊息(灰底部分)。

/// Abstract Factory class
public
abstract class AbstractFactory<F,T> where T:F, new()
{

  
public abstract F Create();
}

/// Factory class
public
class CarFactory<F,T> : AbstractFactory<F,T> where T:F, new()
{
 
public override F Create()
  {
   
Console.WriteLine("Use Abstract Factory method...");
   
return new T();
  }
}


使用方式:
CarFactory<ICar, Focus> Factory1 = new CarFactory<ICar, Focus>();
ICar _focus = Factory1.Create();
_focus.Color =
Color.Silver;
_focus.Drive();




5.       顯示結果

1.測試一般Factory方法
I am driving Silver Focus (FORD)

2.
測試靜態Factory的方法
I am driving Silver Focus (FORD)

3.測試覆寫Abstract Factory的方法
Use Abstract Factory method...
I am driving Silver Focus (FORD)


6.      End

沒有留言:

張貼留言