我已经实现了工厂模式,如下所示。
但是,由于各个类是公共的,因此没有什么可以阻止某人直接实例化它们。
这个对吗?如何确保仅通过工厂创建具体类?
namespace MRS.Framework
{
public abstract class DataSource
{
public override string ToString()
{
return "DataSource";
}
}
public class XMLDataSource : DataSource
{
}
public class SqlDataSource : DataSource
{
}
public class CSVDataSource : DataSource
{
public int MyProperty { get; set; }
public override string ToString()
{
return "CSVDataSource";
}
}
}
工厂实施
namespace MRS.Framework
{
public abstract class DataSourceFactory
{
public abstract DataSource CreateDataSource(DataSourceType datasourcetype);
}
public class CSVDataSourceFactory : DataSourceFactory
{
public CSVDataSourceFactory()
{
}
public override DataSource CreateDataSource(DataSourceType datasourcetype)
{
return new CSVDataSource();
}
}
public class XMLDataSourceFactory : DataSourceFactory
{
public override DataSource CreateDataSource(DataSourceType datasourcetype)
{
return new XMLDataSource();
}
}
public class SqlDataSourceFactory : DataSourceFactory
{
public override DataSource CreateDataSource(DataSourceType datasourcetype)
{
return new SqlDataSource();
}
}
}
主要的
static void Main(string[] args)
{
DataSourceFactory datasourcefactory = new CSVDataSourceFactory();
CSVDataSource ds = (CSVDataSource)datasourcefactory.CreateDataSource(DataSourceType.CSVDataSource);
CSVDataSource myds = new CSVDataSource();
Console.WriteLine(ds.ToString());
Console.WriteLine(myds.ToString());
Console.ReadLine();
}