1. 工厂方法和抽象工厂不同 ,抽象工厂解决的问题是一个系列的对象的创建,而工厂方法解决的是某个对象的创建。 抽象工厂生成的实例是在抽象工厂类中实现, 工厂方法则是使一个类的实例化延迟到其子类
2. 举例
还是数据库访问.
public abstract class DBAccesss
{
public abstract void Open();
}
public class SQLDBAccess:DBAccesss
{
public override void Open()
{
Console.WriteLine("Open SQL SERVER DATABASE!");
}
}
public class ORADBAccess:DBAccesss
{
public override void Open()
{
Console.WriteLine("Open ORACLE!");
}
}
public abstract class DBFactory
{
public abstract DBAccesss Create();
}
public class SQLDBFactory:DBFactory
{
public SQLDBAccess Create()
{
return new SQLDBAccess();
}
}
public class ORADBFactory:DBFactory
{
public ORADBAccess Create()
{
return new ORADBAccess();
}
}
<appSettings>
<add key="factoryName" value="SQLDBFactory"></add>
</appSettings>
public class App
{
public static void Main(string[] args)
{
string strfactoryName = ConfigurationSettings.AppSettings["factoryName"];
DBFactory factory;
factory = (DBFactory)Assembly.Load("FactoryMethod").CreateInstance("FactoryMethod." + strfactoryName);
DBAccesss dBAccesss = factory.Create();
dBAccesss.Open();
}
}
这样就可以通过dbaccess进行数据访问了.