个人不善于表达 思路见于代码 [欢迎大神拍砖批评指点]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Reflection;
namespace SelfToolsHelper
{
public interface Ilog
{
void CreateLog();
}
public class EventLog : Ilog
{
public void CreateLog()
{
Console.Write("Create EventLog");
}
}
public class TxtLog : Ilog
{
public void CreateLog()
{
Console.Write("createTxtLog");
}
}
public class DiskLog : Ilog
{
public void CreateLog()
{
Console.Write("Create DiskLog");
}
}
public interface IFactory
{
Ilog CreateLogFactory();
}
public class EventFactory : IFactory
{
public Ilog CreateLogFactory()
{
return new EventLog();
}
}
public class TexFactory : IFactory
{
public Ilog CreateLogFactory()
{
return new TxtLog();
}
}
public class DiskFactory : IFactory
{
public Ilog CreateLogFactory()
{
return new DiskLog();
}
}
//思考 要是有1w个 log 那 我要建立两万个class (log and factory) ,多付出1w的工作量。
//是否可以优化我的factory方法?
public class FactoryNew<T>
{
public object CreateLogInstance()
{
return Activator.CreateInstance<T>();
}
}
public class FactoryTEST
{
public void TEST()
{
IFactory factory = new DiskFactory();
Ilog log = factory.CreateLogFactory();
log.CreateLog();//面向接口抽象,打印出:Create DiskLog
}
public void TestNew()
{
FactoryNew<EventLog> eventfact =new FactoryNew<EventLog> ();
Ilog log = eventfact.CreateLogInstance() as EventLog;
log.CreateLog();
}
public void TestNewSecond()
{
FactoryNew<DiskLog> diskFactory = new FactoryNew<DiskLog>();
Ilog log = diskFactory.CreateLogInstance() as DiskLog;
log.CreateLog();
}
//以上两个方法是在我知道 到底是使用哪种log方法的测试。、
//现在我不知道我到底要实例化哪种log 而是读取配置文件 来动态创建 这样该怎么办?
//思路 我应该从配置文件里面知道我到底改实例一个什么泛型的工厂 就是说我应该传递什么类型进入 泛型工厂?
// 假如 配置在了config文件中。
//1<appSettings>
//<add key="logtype" value="EventLog"></add>
//</appSettings>
public void TestNewThrid()
{
string strfactoryName = ConfigurationSettings.AppSettings["logtype"];
#region 此部分是思考过程
object o= Activator.CreateInstance(Assembly.GetCallingAssembly().FullName, strfactoryName);
Type t = o.GetType();
//得带log type。 然后根据logtype 再声明 facttorynew<T>;
object obj =Assembly.Load(Assembly.GetCallingAssembly().FullName).CreateInstance(strfactoryName);
// FactoryNew < typeof(obj) > diskFactory = new FactoryNew< typeof(obj) >(); 走不通。
// obj.调用方法。。。。。。。 失败了!
//思考,我为什要先创建factory 再创建log?!!! 我的目的是创建Log 。额 log log已经创建了。。。。
////////////////////////////////////// 这里才是真正实现,注意 配置config的时候直接使用 log Type!跳过Factory
Ilog logObj = Assembly.Load(Assembly.GetCallingAssembly().FullName).CreateInstance(strfactoryName) as Ilog;
logObj.CreateLog();//搞定。
//////////////////////////////////////
#endregion
}
}
}
// 参考资料 http://terrylee.cnblogs.com/archive/2006/01/04/310716.html
2013年9月26日 14:25:51