简体   繁体   中英

What's the best way to define an independent method to be reusable by two non-related classes?

I've two classes that need to use the same method and I believe inheritance is overkill since this is the only thing in common: there are no relations and the operation is very specific. The method to be reused just take two parameters and calculate an operation with them.

It sounds like a utility method. So, I think a separate class containing that method as a static method would do the trick

Composition is a possible solution here. The 2 classes could be passed on one instance of a 'helper' class with your operation.

通常,我会为这种事情创建一个实用程序类-最有可能使用静态方法。

如果该方法不使用任何实例字段:将其设为静态并将其移至某些实用程序类中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM