删除重复的代码,最有效的方法我们有3种在我们的项目属性:的CategoryAttribute,ProductAttribute和ProductTypeAttribute。这些不在我们的控制范围之内,因为它们来自自动生成的类,并且可能包含不同类型的属性值,例如text,number or image。现在,每个属性都有自己的策略来检索attributeValue。为简单起见,我们假设他们全部3个都有TextStrategy,NumberStrategy和ImageStrategy。从多种策略
实施例的策略:
@Component
public class CategoryImageAttributeStrategy implements CategoryAttributeStrategy {
@Override
public boolean isApplicable(CategoryAttribute attribute) {
return attribute.getImage() != null;
}
@Override
public Object getAttributeValue(CategoryAttribute attribute) {
//return attribute value here
//may be different or may be the same
//for ProductImageAttributeStrategy and ProductTypeImageAttributeStrategy
}
}
尽管取得图像值可以是用于所有这些不同的,获取文本值是相同的,我们最终3类的几乎相同的代码和我真的真的不喜欢复制代码。
我想过为每个策略类型创建一个抽象类/默认界面,例如DefaultTextStrategy所有3种文本策略都会继承,并使用提供的默认代码或使用自己的实现覆盖它,但是我对此方法并不满意,因为它需要为如此简单的任务创建更多的类。
也许是有可能将相同类型的策略(如图像)合并为一个?
我真的很想听听更多有经验的人在这个问题上有什么要说的,因为我想学习和改进。
提前感谢您的时间。
问题是(正如我在原始文章中提到的那样),CategoryAttribute,ProductAttribute等是基于xsd模式的自动生成类,我无法控制它们,所以我不能让它们扩展别的东西。我只喜欢3种策略,但是在策略类中,我必须采用Object参数并检查它的instanceof(找出它的属性类型),看起来有点脏。至少我认为这是3个instanceof的适用方法是有点儿。 – Sikor