我有一个混蛋模板方法实现。它不是具有子类实现的基类,而是 util 类上的静态方法,该方法采用其委托的接口。我想将其重构为更常见的模式,这样我就可以停止传递 Domain 类。
我认为第一步是将模板转换为对象方法,但随后我对如何将我的 5 个 Helper 实现(未显示)移动到新 Template 对象的子类中失去了灵感。
public interface Helper
{
void doFirstThing(Domain d);
void doSecondThing(String id);
}
public class UtilClass
{
public static void template(Domain d, Helper h, String who)
{
//begin database transaction
try
{
//some logic
h.doFirstThing(d);
//more computation
h.doSecondThing(d.getId());
//database commit();
}
finally
{
//if transaction open database rollback();
}
}
}
public class Domain
{
public String getId()
{
return "value";
}
}
类似于下面的内容...
public abstract class TemplateX
{
protected Domain _domain;
protected TemplateX(Domain domain)
{
_domain = domain;
}
protected abstract void DoFirstThing();
protected abstract void DoSecondThing();
public void DoIt(string who)
{
//begin database transaction
try
{
//some logic
DoFirstThing();
//more computation
DoSecondThing();
//database commit();
}
finally
{
//if transaction open database rollback();
}
}
}
public class Implementation1 : TemplateX
{
public Implementation1(Domain domain) : base(domain)
{
}
protected override void DoFirstThing()
{
//code from helper class here
}
protected override void DoSecondThing()
{
//code from helper class here
}
}
我又想了想,想出了以下步骤。
用方法对象替换方法。将助手排除在构造函数参数之外。我还跳过了有关创建局部变量字段的部分。当我想要完成时,自动重构做得非常好。
内联静态方法。
使实现成为新 MethodObject 的子类。 这涉及添加/修改构造函数。
在创建方法对象并使用实现调用的情况下,只需创建实现并调用模板方法即可。
new MethodObject(d, who).template(new Implementation(d, who));
成为
Implementation impl = new Implementation(d, who);
impl.template(impl);