简体   繁体   English

扩展多个Java类而不重复

[英]Extend multiple Java classes without duplication

I have a Java class that can extend either of two third-party classes, which I cannot change. 我有一个Java类,可以扩展两个第三方类中的任何一个,但不能更改。 I can choose either of these implementations at compile time with no changes to my class other than the "extends" declaration. 我可以在编译时选择这些实现中的任何一个,除了“ extends”声明外,无需对我的类进行任何更改。 Unfortunately I need to choose which implementation to use at runtime, not at compile time. 不幸的是,我需要选择在运行时而不是在编译时使用哪种实现。 What's the best way to select between these two implementations at run-time without duplicating the entire derived class? 在运行时在这两种实现之间进行选择而不复制整个派生类的最佳方法是什么?

It sounds like you require a Strategy pattern . 听起来您需要一个Strategy模式

the strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime. 策略模式(也称为策略模式)是一种特殊的软件设计模式,由此可以在运行时选择算法。

So your Java class should contain a reference to one of the two classes that you want to use, and bridge to that implementation. 因此,您的Java类应该包含对要使用的两个类之一的引用,并桥接到该实现。 The implementation you choose can be selected at runtime. 您选择的实现可以在运行时选择。 It's not clear from your problem description, but if your two 3rd-party classes implement a common interface, then your Java class would most likely implement this interface and you can directly map to the referenced 3rd-party class. 从问题描述中还不清楚,但是如果您的两个3rd-party类实现一个公共接口,则您的Java类很可能实现此接口,并且您可以直接映射到引用的3rd-party类。

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

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