我怎样才能使这种方法可重用?

时间:2016-10-25 15:49:06

标签: java

我有两个使用类似方法的类:

method classA() {
    some variable initialization
    get this common interface In

    try {
        do something
        In.methodAA();

    catch () {
        do something
    }
}


method classB() {
    some variable initialization
    get this common interface In

    try {
        do something
        In.methodBB()

    catch () {
        do something 
    }
}

如果可能的话,我想在父类中放置一个方法,因为主要区别在于接口上调用的方法。怎么能实现呢?

我正在使用java7。

谢谢

3 个答案:

答案 0 :(得分:1)

我会使用第三个实用程序类

static method classC(classType){

    some variable initialization
    get this common interface In
    try {
      do something

      if (classType is A)
        In.methodAA()
      else 
        In.methodBB()

    } catch () {
      do something
    }
}

答案 1 :(得分:0)

我会使用由A和B类实现的通用接口

interface Behaviour {
    void execute();
}

public class A implements Behaviour {
    @Override
    public void execute() {
        // do method A logic
    }
}

public class B implements Behaviour {
    @Override
    public void execute() {
        // do method B logic
    }

}

public class TemplateClass {
    private Behaviour behaviour;

    public TemplateClass(Behaviour behaviour) {
        this.behaviour = behaviour;
    }

    public void commonMethod() {
        try {
            // do something
            // ..

            // call specific logic
            behaviour.execute();
        } catch (Exception e) {
            // handle ex
        }

    }
}

用法

//using A class
TemplateClass polymorphicVariable = new TemplateClass(new A());
polymorphicVariable.commonMethod();

//using B class
polymorphicVariable = new TemplateClass(new B());
polymorphicVariable.commonMethod();

答案 2 :(得分:-1)

您需要提供abstract方法,以便公共接口知道要调用的内容,例如:

abstract class Parent {
  public void job() {
    try {
      doJob();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  protected abstract void doJob();
}

class Child1 extends Parent {
  @Override protected void doJob() {
    /* implementation */
  }
}