我有两个班级ExceptionLog
和DebugLog.
public class ExceptionLog {
public static String StackTrace {get; set;}
public static String ClassName {get; set;}
public static String MethodName {get; set;}
public static String LogType {get;set;}
public static Exception ex {get;set;}
public Static void Debug(Exception ex)
{
logType = 'EXCEPTION';
ex = ex;
log();
}
public Static void log()
{
try
{
extractException();
writeToObject();
}
catch(Exception e)
{
//new ExceptionLog().Module('LogException').log(e);
}
}
public static void extractException()
{
// Logic here
}
public static void writeToObject()
{
// data save to object logic here
}
}
和
public class DebugLog {
public static String LogType {get;set;}
public static String DebugMessage {get;set;}
public Static void Debug(String message)
{
Debug(null, message);
}
public Static void Debug(LoggingLevel level, String message)
{
if(level != null )
{
LogType = String.valueOf(level);
}
DebugMessage = message;
log();
}
public Static void log()
{
// Log logic here
}
}
我要实现的是,编写一个控制器类,该类将决定需要调用哪种debug
方法
public class Log {
public void Debug(String message)
{
DebugLog.Debug(message);
}
public void Debug(loggingLevel loggingLevel, String message)
{
DebugLog.Debug(loggingLevel, message);
}
public void Debug(Exception ex)
{
ExceptionLog.Debug(ex);
}
}
也就是说,如果我在debug方法中传递Exception,它将调用ExceptionLog.Debug(ex)
,否则将从DebugLog
类调用debug方法。
我如何才能更优雅地设计类,或者在这里适合任何设计模式?
答案 0 :(得分:1)
您可以发送无类型的参数并在Log类中找到类型,如下所示:
public class Log {
public void debug(Object genericLog){
if(genericLog instanceof String){
DebugLog.Debug(String.valueOf(message));
}
else if(genericLog instanceof Exception){
ExceptionLog.Debug((Exception)genericLog);
}
else if(genericLog instanceof DebugWrapper){
DebugWrapper wrapper = (DebugWrapper)genericLog;
DebugLog.Debug(wrapper.loggingLevel, wrapper.message);
}
else{
//do whatever
}
}
public void debug(String message, LoggingLevel loggingLevel){
debug(wrapLog(message, loggingLevel));
}
public class DebugWrapper{
public String message;
public LoggingLevel loggingLevel;
public DebugWrapper(String message, LoggingLevel loggingLevel){
this.message = message;
this.loggingLevel = loggingLevel;
}
}
public DebugWrapper wrapLog(String message, LoggingLevel loggingLevel){
return new DebugWrapper(message, loggingLevel);
}
}
或者,您可以实现Apex Callable接口,该接口旨在处理通用参数映射。您的课程将定义一个call(String action, Map<String, Object> args)
方法。通过开关盒传递动作将确定调用哪个方法。