design-patterns - 顶点中的条件方法链接
问题描述
我有一个类LogException
public class LogException extends Exception {
public String ModuleName {get; set;}
public String StackTrace {get; set;}
public String ClassName {get; set;}
public String MethodName {get; set;}
public String ExceptionCause {get; set;}
public void log(Exception ex)
{
try
{
extractExceptionData(ex);
writeToObject(ex);
}
catch(Exception e)
{
new LogException().Module('LogException').log(e);
}
}
public LogException Module(String Name)
{
ModuleName = name;
return this;
}
public LogException ExceptionCause(String cause)
{
ExceptionCause = cause;
return this;
}
public void extractExceptionData(Exception ex)
{
try
{
stackTrace = ex.getStackTraceString().substringBefore('\n');
className = stackTrace.substringAfter('.').substringBefore('.');
methodName = stackTrace.substringBefore(':').substringAfter(className).substringAfter('.');
}
catch(Exception e)
{
new LogException().Module('LogException').log(e);
}
}
public void writeToObject(Exception ex)
{
try
{
// insert to object(database) here
}
catch(Exception e)
{
new LogException().Module('LogException').log(e);
}
}
}
我在这里实现了方法链接。因此,我可以调用类似的方法
new LogException().Module('unitTestModule').Log(ex);
new LogException().ExceptionCause('divided by zero').Log(ex);
new LogException().Module('unitTestModule').ExceptionCause('Probably no data in account').Log(ex);
new LogException().ExceptionCause('Probably no data in account').Module('unitTestModule').Log(ex);
我的问题是,我怎样才能实现这个类,以便我只能ExceptionCause
在之后调用Module
?
解决方案
我不会在这里使用方法链接。我只是重写构造函数来填充所需的参数:
public LogException(String module, String exceptionCause) {
}
public LogException(String module) {
this(module, null);
}
// etc.
你在这里唯一不能做的就是有两个构造函数,它们都接受一个String
参数——你必须愿意通过额外的可选参数来定义所需的层次结构,就像exceptionCause
这里一样。
参考文档是Apex Constructors。
推荐阅读
- flutter - Flutter web with incompatible plugins
- bash - 包含空格的 Bash 脚本参数不起作用
- modelica - Integration in OpenModelica
- css - 是否可以保持端口视图和容器自动调整?
- javascript - Formspree Profanity Filter
- laravel - User session is still valid after a database refresh
- react-native - React native and webassembly issues
- python - How to create an instance in Python using another thread (QRunnable)
- javascript - material-ui : 自动启用暗模式
- python - how can I change pytube file to exe