抽象类,OOP 设计模式 [英] Abstract Class, OOP Design Pattern

查看:39
本文介绍了抽象类,OOP 设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为操作"的抽象类并且这个类有一个叫做Prepare"的抽象方法.

I have an abstract class called "Operation" and this class has an abstract method called "Prepare".

public abstract class Operation {
    public abstract void prepare() throws Exception;
    public abstract void run() throws Exception;
    // other stuff here that's not abstract
    public void printHelloWorld() { 
         System.out.println("Hello World!");
    }

}

唯一的问题是一些操作"(一些扩展 Operation 的类需要准备参数(一些需要整数,有些需要字符串,有些需要更复杂的数据类型..所以它并不总是整数)

The only issue is that some things that are "Operation" ( some classes that extends Operation ) need arguments to prepare ( some need ints, some need String, some need more complex data types..so it's not always an int )

public class Teleportation extends Operation {
   @Override
   public void prepare(int capacityRequired ) throws Exception {
        // do stuff
   }
   @Override
   public void run() throws Exception {
   }
}

我使用什么 OOP 模式来实现这一点以及如何设置此代码?

What OOP pattern do I use to achieve this and how do I set up this code ?

理想情况下,我想准备和运行这样的操作:

Ideally, I want to prepare and run operations like this :

for (Operation operation : operations ) {
  operation.prepare();
  operation.run(); 
}

假设我使用这个解决方案:

Assuming I use this solution :

 public class Teleportation extends Operation {
       private int cReq;
       public void setCapacityRequired(int cReq) {
         this.cReq = cReq;
       }
       @Override
       public void prepare() throws Exception {
                // I can do the preparation stuff
                // since I have access to cReq here
       }
       @Override
       public void run() throws Exception {
       }
    }

然后 - 我想知道是否有可能避免这种情况:

Then - I wonder if it's possible to avoid this :

 for (Operation operation : operations ) {
      if (operation.getClass().isInstanceOf(Teleporation.class)) {
               ((Teleporation)operation).setCapacityRequired( 5 );
      }
      operation.prepare();
      operation.run(); 
    }

推荐答案

我建议有一个额外的构造函数,您可以在其中添加实现所需的必要数据并将其存储在类实现的字段中.

I would recommend having an additional constructor where you can add the necessary data that the implementation requires and store it in fields for the class implementation.

例如:

public class Teleportation extends Operation {
    private final int capacityRequired;
    public Teleportation(int capacityRequired) {
        this.capacityRequired = capacityRequired;
    }
    public void prepare() throws Exception {
    // do stuff using the capacityRequired field...
    }
}

这种方法也适用于更复杂的参数.

This approach applies for more complex parameters as well.

这篇关于抽象类,OOP 设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆