This design patterns guides to create a wrap around existing class to reuse existing class for a new requirement.
Assume, I have two logging classes named WriteLogsToLocalFile
and WriteLogsToServer
.
class WriteLogsToLocalFile
{
public void Log(string fileName, string message)
{
//write logs to file
}
}
class WriteLogsToServer
{
public void Log(string urL, string message, string token)
{
//call rest API with oAuth
// Note: here token is used for oAuth
}
}
static void Main(string[] args)
{
WriteLogsToLocalFile fileLogs = new WriteLogsToLocalFile();
fileLogs.Log("hello.xml", "login success");
WriteLogsToServer serverLogs = new WriteLogsToServer();
serverLogs.Log("https://server.logs/upload", "login success", "oAuthToken");
}
Here user is manually creating objects to write logs separately to local file and server.My requirement is to create a common class for logging, so that client can call common class. The common class should blindly recurse through list of loggers to log message.
In below code, a new interface ILog
is not compatible with WriteLogsToLocalFile
and WriteLogsToServer
. We created WriteLogsToServerAdapter
and WriteLogsToServerAdapter
. Logging
is helper class.
interface ILog
{
void Log(string message);
}
// this class can not implement interface thus created Adapter
class WriteLogsToLocalFile
{
public void Log(string fileName, string message)
{
//write logs to file
}
}
// this class can not implement interface thus created Adapter
class WriteLogsToServer
{
public void Log(string urL, string message, string token)
{
//call rest API with oAuth
// Note: here token is used for oAuth
}
}
class WriteLogsToLocalFileAdapter : ILog
{
string location;
WriteLogsToLocalFile fileLog = new WriteLogsToLocalFile();
public WriteLogsToLocalFileAdapter(string location)
{
this.location = location;
}
public void Log(string message)
{
fileLog.Log(this.location, message);
}
}
class WriteLogsToServerAdapter: ILog
{
string oAuthToken;
string location;
WriteLogsToServer serverLogs = new WriteLogsToServer();
public WriteLogsToServerAdapter(string token, string location)
{
this.oAuthToken = token;
this.location = location;
}
public void Log(string message)
{
serverLogs.Log(this.location, message, this.oAuthToken);
}
}
class Logging
{
ILog fileLogs = new WriteLogsToLocalFileAdapter("index.log");
ILog serverLogs = new WriteLogsToServerAdapter("oAuthToken", "apiPath");
public void Log(string message)
{
fileLogs.Log(message);
serverLogs.Log(message);
}
}
static void Main(string[] args)
{
Logging logger = new Logging();
logger.Log("login success");
}