2
我想實現工廠模式架構。我用參數化函數創建了接口。將參數傳遞給C#中的工廠模式架構#
1)步驟1:
public interface IDatabase
{
bool Create(string userId,string password,string host,string dbName);
bool Delete(string userId, string password, string host, string dbName);
}
步驟2:
此接口下面類中實現在: -
public class IntialDBSetup : IDatabase
{
public bool Create(string userId, string password, string host, string dbName)
{
SqlConnection con = new SqlConnection("Data Source=" + host + ";uid=" + userId + ";pwd=" + password + "");
try
{
string strCreatecmd = "create database " + dbName + "";
SqlCommand cmd = new SqlCommand(strCreatecmd, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
var file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ScriptLocation"]));
string strscript = file.OpenText().ReadToEnd();
string strupdatescript = strscript.Replace("[OWpress]", dbName);
var server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(strupdatescript);
con.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool Delete(string userId, string password, string host, string dbName)
{
throw new NotImplementedException();
}
}
步驟3:
創建工廠類
public class DBFactory
{
public static IDatabase DbSetup(string DbType, string userId, string password, string host, string dbName)
{
try
{
if (DbType == DBTypeEnum.IntialDB.ToString())
{
return new IntialDBSetup();
}
}
catch (Exception ex)
{
throw new ArgumentException("DB Type Does not exist in our Record");
}
return null;
}
}
在這裏我想傳遞一些參數給我的班級,我可以得到這個嗎?
不應該在''InitialDBSetup()''上調用'Create'方法嗎? –
工廠通常負責返回實例化對象。這就是你的做法。我想你要求你的工廠對該對象執行一個動作('Create')?通常這就是工廠的人會做的事情。不是說你在做什麼不好,我只是不認爲你真的需要一個工廠。 – Jonesopolis