oop - 从两个不同的类有条件地调用方法
问题描述
我有两个班级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);
}
}
也就是说,如果我在调试方法中传递 Exception ,它将调用ExceptionLog.Debug(ex)
else 它将从DebugLog
类中调用调试方法。
我怎样才能更优雅地设计课程或任何适合这里的设计模式?
解决方案
您可以发送一个未键入的参数并在 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)
定义一个方法。通过 switch case 传递操作将确定调用哪个方法。
推荐阅读
- ruby-on-rails - 自动过滤索引页面上的帐户
- sql - 如何为一组用户找到特定日期之后的下一个日期?
- javascript - 按类别组织项目
- javascript - 元素不能在 DOM 中显示
- javascript - WooCommerce- 画布/绘画的 SizeInfo 按钮。[PHP,Javascript,html,css]
- python - 使用 ACR1252U NFC 标签阅读器读取 NTag213 上的所有记录
- java - 从资源文件中获取 String 和 Drawable 到 Fragment View Model 类
- angular - ngFor 迭代 n+1 次以获得至少 1 个值
- python - 在 Python 中将序列拆分为单个步骤的最优雅方法
- r - 在 R 中的地图上显示时间序列预测的预测区间(空间建模)