解决方法一:使用策略模式
// 创建策略接口
interface Strategy {
void execute();
}
// 实现具体的策略类
class StrategyA implements Strategy {
@Override
void execute() {
// 执行特定的操作A
}
}
class StrategyB implements Strategy {
@Override
void execute() {
// 执行特定的操作B
}
}
// 创建上下文类
class Context {
private Strategy strategy;
Context(Strategy strategy) {
this.strategy = strategy;
}
void executeStrategy() {
strategy.execute();
}
}
// 使用示例
public static void main(String[] args) {
Strategy strategy = new StrategyA(); // 或者根据需要创建StrategyB
Context context = new Context(strategy);
context.executeStrategy();
}
解决方法二:使用函数式编程(Java 8+)
// 定义一个函数式接口,表示特定操作
interface SpecificOperation {
void execute();
}
// 创建一个工具类,封装通用操作
class Utils {
static void performSpecificOperation(SpecificOperation operation) {
operation.execute();
}
}
// 使用示例
public static void main(String[] args) {
Utils.performSpecificOperation(() -> {
// 执行特定的操作
});
}
这两种解决方法都可以避免为每个特定类型创建子类,而是通过传递具体的实现来实现特定的操作。这样可以减少类的数量,提高代码的灵活性和可维护性。