對於產生器模式我這裡以生產單車為例進行講解,單車由車輪與車架組成,由不同樣式的車輪與不同樣式的車架就可以組裝成不同的單車(如賽車,山地車等),下面的程式進行說明:
/**//// <summary>定義自行車架構</summary>
public struct Bike
{
private string bikeWheel;
private string bikeFrame;
public Bike(string wheel,string frame)
{
this.bikeWheel = wheel;
this.bikeFrame = frame;
}
public string GetBike
{
get
{
return bikeWheel + bikeFrame;
}
}
}
/**//// <summary>定義介面</summary>
public interface MainInterface
{
void CreateWheel(string bikeType);
void CreateFrame(string bikeType);
Bike GetBike();
}
/**//// <summary>創建自行車的各個組件</summary>
public class ConcreteClass : MainInterface
{
string wheel;
string frame;
/**//// <summary>創建自行車的車輪</summary>
public void CreateWheel(string bikeType)
{
switch(bikeType)
{
case "山地車":
wheel="山地車的車輪為@@@";
break;
case "賽車":
wheel="賽車的車輪為***";
break;
}
}
/**//// <summary>創建自行車的車架</summary>
public void CreateFrame(string bikeType)
{
switch(bikeType)
{
case "山地車":
frame="山地車的車架為^^^";
break;
case "賽車":
frame="賽車的車架為+++";
break;
}
}
/**//// <summary>這裡用於獲得自行車</summary>
public Bike GetBike()
{
return new Bike(wheel,frame);
}
}
/**//// <summary>用於組裝成不同樣式的自行車</summary>
public class CreateBike
{
private MainInterface objMain;
private string bikeType;
public CreateBike(MainInterface objMain,string bikeType)
{
this.objMain = objMain;
this.bikeType = bikeType;
}
public void Create()
{
objMain.CreateWheel(bikeType);
objMain.CreateFrame(bikeType);
}
}
下面來看看調用:
string bikeType="山地車";
ConcreteClass objCon = new ConcreteClass();
CreateBike objCB = new CreateBike(objCon,bikeType);
objCB.Create();
Bike objB = objCon.GetBike();
Response.Write(objB.GetBike);
下面來比較抽象原廠模式與產生器模式的區別:
以生產單車為例,抽象原廠模式獲得的是不同名牌的單車而不管單車是由什麼組件組裝而成的;而產生器模式獲得是不同樣式的單車,所關心的是單車組成組件的構成.所以看出抽象原廠模式獲得是一系列相關的類(如鳳凰牌單車,XX牌自車等)而產生器模式獲得的是提供給它資料(如上例中的“山地車“)一步一步構建的一個複雜的對象(即山地車)