There are four 4 thing need to keep in mind:
// Example : LogError
public interface ILog // 1-Product
{
void LogError();
}
class WordLog : ILog // 2- ConcreteProduct
{
public void LogError()
{
Console.WriteLine("log error in word");
}
}
class CsvLog : ILog // 2- ConcreteProduct
{
public void LogError()
{
Console.WriteLine("log error in csv");
}
}
class SqlLog : ILog // 2- ConcreteProduct
{
public void LogError()
{
Console.WriteLine("log error in sql");
}
}
public abstract class LogFactory //3- Creator
{
public abstract ILog LogCommand(string logType);
}
class ConcreteLog : LogFactory // ConcreteCreator
{
public override ILog LogCommand(string logType)
{
switch (logType)
{
case "word":
return new WordLog();
case "csv":
return new CsvLog();
case "sql":
return new SqlLog();
default:
throw new ApplicationException(string.Format("logType '{0}' cannot be created", logType));
}
}
}
public class Client
{
public void Test()
{
var factory = new ConcreteLog();
for (int i = 0; i < 3; i++)
{
if (i == 1)
{
var command = factory.LogCommand("word");
command.LogError();
}
if (i == 2)
{
var command = factory.LogCommand("csv");
command.LogError();
}
if (i == 3)
{
var command = factory.LogCommand("sql");
command.LogError();
}
}
}
}
- Product
This defines the interface of objects the factory method creates
- ConcreteProduct
This is a class which implements the Product interface.
- Creator
This is an abstract class and declares the factory method, which returns an object of type Product.
- ConcreteCreator
This is a class which implements the Creator class and overrides the factory method to return an instance of a ConcreteProduct.
// Example : LogError
public interface ILog // 1-Product
{
void LogError();
}
class WordLog : ILog // 2- ConcreteProduct
{
public void LogError()
{
Console.WriteLine("log error in word");
}
}
class CsvLog : ILog // 2- ConcreteProduct
{
public void LogError()
{
Console.WriteLine("log error in csv");
}
}
class SqlLog : ILog // 2- ConcreteProduct
{
public void LogError()
{
Console.WriteLine("log error in sql");
}
}
public abstract class LogFactory //3- Creator
{
public abstract ILog LogCommand(string logType);
}
class ConcreteLog : LogFactory // ConcreteCreator
{
public override ILog LogCommand(string logType)
{
switch (logType)
{
case "word":
return new WordLog();
case "csv":
return new CsvLog();
case "sql":
return new SqlLog();
default:
throw new ApplicationException(string.Format("logType '{0}' cannot be created", logType));
}
}
}
public class Client
{
public void Test()
{
var factory = new ConcreteLog();
for (int i = 0; i < 3; i++)
{
if (i == 1)
{
var command = factory.LogCommand("word");
command.LogError();
}
if (i == 2)
{
var command = factory.LogCommand("csv");
command.LogError();
}
if (i == 3)
{
var command = factory.LogCommand("sql");
command.LogError();
}
}
}
}
No comments:
Post a Comment