简体   繁体   English

分离常用方法的最佳方法

[英]best way to seperate common methods

I have some common methods for two classes and maybe for others in the future. 我有一些常用的方法可以用于两个类,也可能用于将来的其他类。 Therefore I do not want to copy same methods in all classes. 因此,我不想在所有类中复制相同的方法。 I thought to create a utility class and put these methods inside and send the necessary data as a parameter. 我想创建一个实用程序类并将这些方法放入其中并将必要的数据作为参数发送。 But I read about using utility class violate OOP. 但我读到使用实用程序类违反OOP。

As a second, I was thinking to apply strategy pattern but I do not need to change behaviour of the method in the runtime, it will work same for both classes therefore it looks it does not suit to my problem. 作为第二个,我正在考虑应用策略模式,但我不需要在运行时更改方法的行为,它将对两个类都一样,因此看起来它不适合我的问题。

Do you have any idea what could be the best approach for this situation or which design pattern could be applied? 您是否知道这种情况的最佳方法是什么,或者可以应用哪种设计模式?

It's not bad to violate OOP for something that is really a utility class. 对于实际上是实用类的东西来说违反OOP并不坏。

Almost all frameworks (spring, hibernate you_name_it) do that to some extend. 几乎所有的框架(spring,hibernate you_name_it)都在某种程度上做到了这一点。

Furthermore, if you later plan to support your code, composition is much easier to refactor / support than to maintain inheritance in your classes. 此外,如果您以后计划支持您的代码,则构造比重构/支持更容易维护类中的继承。

public class Baseclass
{
    public Baseclass(){
        //init baseclass;
    }

    public void commonMethod(){
        //do stuff;
    }
}


public class AnyObject extends Baseclass
{
    public AnyObject(){
        super();
    }
}

Simple example 简单的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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