有这种模式吗?公共基类,对某些子类具有特殊操作

Fre*_*eit 1 java design-patterns

我有代码,当给出一个东西时,它需要理清它是什么特定的东西,然后采取基于此的特殊行动.可能的类别都是desc

public void doSomething(BaseThing genericThing) 
{
  if (genericThing instanceof SpecificThing)
  {
    SpecificThingProcessor stp = new SpecificThingProcessor((SpecificThing) genericThing);
  }
  else if (genericThing instanceof DifferentThing)
  {
    DifferentThingProcessor dtp = new DifferentThingProcessor((DifferentThing) genericThing);
  }
  else if (genericThing instanceof AnotherThing){
    AnotherThingProcessor atp = new AnotherThingProcessor((AnotherThing) genericThing);
  }
  else
  {
    throw new IllegalArgumentException("Can't handle thing!");
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有一种模式或更好的方法来处理这个?不幸的是,正在执行的操作不适合围绕BaseThing进行泛化,它们必须针对每个特定类别的事物进行.

Jus*_*ner 11

我能想到的最好的选择是将功能抽象到接口,并让每个类型实现该接口.

如果你根据类型添加一些关于你想要做的事情的更多细节,我可以提出一个更好的建议(可能有一些示例代码).

编辑

编辑后,肯定有一个明确的方法来做到这一点.每个处理器将实现特定的接口:

public interface IProcessor
{
    void Process();
}

public class SpecificThingProcessor : IProcessor
{
    public void Process() { /* Implementation */ }    
}

public class DifferentThingProcessor : IProcessor
{
    public void Process() { /* Implementation */ }
}

public class AnotherThingProcessor : IProcessor
{
    public void Process() { /* Implementation */ }
}
Run Code Online (Sandbox Code Playgroud)

每个BaseThing必须实现一个返回特定处理器的方法:

public abstract class BaseThing
{
    public abstract IProcessor GetProcessor();
}

public class SpecificThing : BaseThing
{
    public override IProcessor GetProcessor()
    {
        return new SpecificThingProcessor();
    }
}

public class DifferentThing : BaseThing
{
    public override IProcessor GetProcessor()
    {
        return new DifferentThingProcessor();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你的方法将是:

public void doSomething(BaseThing genericThing)
{
    IProcessor processor = genericThing.GetProcessor();
    processor.Process();
}
Run Code Online (Sandbox Code Playgroud)

  • 到目前为止,我真的没有看到OP的问题暗示需要一个界面,更多的信息可以清除它 (2认同)

egl*_*ius 10

您应该在BaseThing中定义一个方法,以便被特定的Things覆盖.

换句话说,您应该使用虚函数.


正在执行的操作不在通用事物上执行.根据其特定类型,需要实例化"Producer"类以处理正确类型的事物.从BaseThing子类调用Producer是不合适的

你仍然可以:thing.GetProcessor(),让每个东西都返回它用于它的特定处理器.处理器当然会实现公共接口或基类.

另一种选择,这会达到我的java限制,但我相信你应该能够沿着这些方向做点什么:

  • 存储类型的列表/字典,处理器构造函数.
  • 获取您收到的genericThing实例的类型
  • 在列表中搜索类型并调用相应的构造函数.

  • 使用术语"虚函数"必然会让一些java开发人员感到困惑. (2认同)