Sometimes, when creating an object it’s more complicated than just calling a constructor. Maybe there is logic that needs to be processed to determine which specific class needs to be returned. Ideally you don’t want to have this logic duplicated throughout your application in case it ever changes. It’s much easier to maintain this logic if it is kept in a single location. One way to do this is to follow the factory pattern.
The idea behind the factory pattern is that you call into a common method to create an instance of a common object. Here is a simple but practical example.
public static class LogFactory
{
// common method that determines which ILog to use
public static ILog GetLog()
{
#if DEBUG
return new LogConsole();
#endif
if (string.Equals(ConfigurationManager.AppSettings["UseSQLLog"], "1"))
{
return new LogSQL();
}
else
{
return new LogFile();
}
}
}public interface ILog
{
void WriteLog(string entry);
}public class LogFile : ILog
{
public void WriteLog(string entry)
{
// write entry to file
}
}public class LogSQL : ILog
{
public void WriteLog(string entry)
{
// write entry to SQL
}
}
public class LogConsole : ILog
{
public void WriteLog(string entry)
{
Console.WriteLine(entry);
}
}
Đặt vé máy bay tại Aivivu, tham khảo
ReplyDeletegiá vé máy bay đi Mỹ khứ hồi
vé máy bay từ mỹ về việt nam hãng ana
giá thuê máy bay từ anh về việt nam
chuyến bay từ pháp về việt nam
Here at this site really the fastidious material collection so that everybody can enjoy a lot.
ReplyDeletebest UX design firms