设计模式学习摘要-抽象工厂

以日志记录实现为例:

具体实现日志类
1。定义一个抽象的日志Log
public abstract class Log
{
   public abstract void Write();
}
2。定义两个具体的日志类
public class EventLog:Log
{
   public override void Write()
   {
      Console.WriteLine("EventLog write sucess !");
   }
}
public class FileLog:Log
{
   public override void Write()
   {
      Console.WriteLine("FileLog write sucess !");
   }
}

具体实现工厂类
1。定义一个抽象工厂类LogFactory
public abstract class LogFactory
{
   public abstract Log Create();
}
2。定义两个具体的工厂类
public class EventFactory:LogFactory
{
   public override EventLog  Create()
   {
      return new EventLog();
   }
}
public class FileFactory:LogFactory
{
   public override FileLog Create()
   {
      return new FileLog();
   }
}


应用程序中调用
public class App
{
   public static void Main(string[] args)
   {
      LogFactory factory=new EventFactory();//
      Log log=factory.Create();//
      log.Write();
   }
}
利用发射机制进一步修改
<appSettings>   
   add key="factoryName" value="EventFactory"></add>
</appSettings>


pubic class App
{
   public static void Main(string[] args)
   {
      string strfactoryName = ConfigurationSettings.AppSettings["factoryName"];    
      LogFactory factory;
      factory = (LogFactory)Assembly.Load("FactoryMethod").CreateInstance("FactoryMethod." + strfactoryName);
      Log log = factory.Create();
      log.Write();
   }
}

参考资料:
http://terrylee.cnblogs.com/archive/2006/01/04/310716.html

posted on 2007-04-10 15:03  散步的蠕虫  阅读(271)  评论(0编辑  收藏  举报

导航