工厂方法
工厂方法
特点:
将对象的创建放在工厂类中,利用抽象原理,将实例化行为延迟到工厂类中
using System;
using System.Collections.Generic;
using System.Text;
namespace OOAD_FactoryMethod
{
class Program
{
static void Main(string[] args)
{
AbsFactory af = new DbFactory();
AbsLog al = af.CreateLog();
Console.WriteLine("日志内容" + al.getLog()[0].Message + "记录时间" + al.getLog()[0].RecordTime);
AbsFactory af2 = new TxtFactor();
AbsLog al2 = af2.CreateLog();
Console.WriteLine("日志内容" + al2.getLog()[0].Message + "记录时间" + al2.getLog()[0].RecordTime);
Console.Read();
}
}
public class Log
{
/// <summary>
/// 构造方法
/// </summary>
/// <param name="msg">日志内容</param>
/// <param name="rt">日志记录时间</param>
public Log(string msg, DateTime rt)
{
this.Message = msg;
this.RecordTime = rt;
}
/// <summary>
/// 日志内容
/// </summary>
private string _message;
public string Message
{
get { return _message; }
set { _message = value; }
}
/// <summary>
/// 日志记录时间
/// </summary>
private DateTime _recordTime;
public DateTime RecordTime
{
get { return _recordTime; }
set { _recordTime = value; }
}
}
public abstract class AbsLog
{
public abstract List<Log> getLog();
public abstract bool InsertLog(Log log);
}
public class DbLog : AbsLog
{
public override List<Log> getLog()
{
List<Log> list = new List<Log>();
list.Add(new Log("DB", DateTime.Now));
return list;
}
public override bool InsertLog(Log log)
{
return true;
}
}
public class TxtLog : AbsLog
{
public override List<Log> getLog()
{
List<Log> list = new List<Log>();
list.Add(new Log("Txt", DateTime.Now));
return list;
}
public override bool InsertLog(Log log)
{
return true;
}
}
public abstract class AbsFactory
{
public abstract AbsLog CreateLog();
}
public class TxtFactor : AbsFactory
{
public override AbsLog CreateLog()
{
return new TxtLog();
}
}
public class DbFactory : AbsFactory
{
public override AbsLog CreateLog()
{
return new DbLog();
}
}
}