这是编写工厂和适配器模式的正确方法吗?

时间:2015-10-01 13:42:26

标签: c# class design-patterns interface

我正在尝试使用我想要学习的适配器和工厂模式,但不确定在实际场景中使用它们的正确方法。

下面是一个用于在三个不同部分编写日志的控制台应用程序。

提前致谢。

这是控制台应用程序

class Program
{
    static void Main(string[] args)
    {
        LogWriterFactory _LogWriterFactory = new LogWriterFactory();

        var data = _LogWriterFactory.SaveData(SaveOption.Database, "Something");
        var email= _LogWriterFactory.SaveData(SaveOption.Email, "Something");
        var text = _LogWriterFactory.SaveData(SaveOption.Text, "Something");

        Console.WriteLine("{0}", data);
        Console.WriteLine("{0}", email);
        Console.WriteLine("{0}", text);
        Console.ReadKey();
    }
}

这是类库

public enum SaveOption
{
    Database = 1,
    Email = 2,
    Text = 3
}

public class LogWriterFactory
{
    public string SaveData(SaveOption option, string Log = "")
    {
        LogWriterAdp _LogWriterAdp = new LogWriterAdp();
        string output;
        switch (option)
        {
            case SaveOption.Database:
                IConnector _SendEmailConnector= new SendEmailConnector();
                output = _LogWriterAdp.Write(_SendEmailConnector, Log);
                break;
            case SaveOption.Email:
                IConnector _WriteInDBConnector = new WriteInDBConnector();
                output = _LogWriterAdp.Write(_WriteInDBConnector , Log);
                break;
            case SaveOption.Text:
                IConnector _WriteInTextConnector= new WriteInTextConnector();
                output = _LogWriterAdp.Write(_WriteInTextConnector, Log);
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
        return output;
    }
}

public class LogWriterAdp
{
    public string Write(IConnector Connector, string Log)
    {
        return Connector.Save(Log);
    }
}

public interface IConnector
{
    string Save(string Log);
}

public class SendEmailConnector : IConnector
{
    public string Save(string Log)
    {
        SendEmail _SendEmail = new SendEmail();
        return _SendEmail.Send(Log);
    }
}

public class WriteInDBConnector : IConnector
{
    public string Save(string Log)
    {
        WriteInDB _WriteInDB = new WriteInDB();
        return _WriteInDB.Save(Log);
    }
}

public class WriteInTextConnector : IConnector
{
    public string Save(string Log)
    {
        WriteInText _WriteInText = new WriteInText();
        return _WriteInText.Write(Log);
    }
}

public class SendEmail
{
    public string Send(string Log)
    {
        return "Data From DatabaseHelper " + Log;
    }
}

public class WriteInText
{
    public string Write(string Log)
    {
        return "Data From WebSiteScanner " + Log;
    }
}

public class WriteInDB
{
    public string Save(string Log)
    {
        return "Data From XmlFileLoader " + Log;
    }
}

Output

我正在尝试使用我想要学习的适配器和工厂模式,但不确定在实际场景中使用它们的正确方法。

0 个答案:

没有答案