在Java中,可以通过以下几种方法来增强类的扩展性:
public interface MyInterface {
void myMethod();
}
public class MyClass implements MyInterface {
@Override
public void myMethod() {
System.out.println("My method implementation");
}
}
public abstract class MyBaseClass {
public abstract void myAbstractMethod();
public void myNonAbstractMethod() {
System.out.println("Non-abstract method implementation");
}
}
public class MyDerivedClass extends MyBaseClass {
@Override
public void myAbstractMethod() {
System.out.println("Derived class method implementation");
}
}
public class MyClass {
private MyComponent myComponent;
public MyClass(MyComponent myComponent) {
this.myComponent = myComponent;
}
public void useComponent() {
myComponent.doSomething();
}
}
public class MyComponent {
public void doSomething() {
System.out.println("Component doing something");
}
}
public interface Strategy {
int calculate(int a, int b);
}
public class AddStrategy implements Strategy {
@Override
public int calculate(int a, int b) {
return a + b;
}
}
public class SubtractStrategy implements Strategy {
@Override
public int calculate(int a, int b) {
return a - b;
}
}
public class Calculator {
private Strategy strategy;
public Calculator(Strategy strategy) {
this.strategy = strategy;
}
public int calculate(int a, int b) {
return strategy.calculate(a, b);
}
}
遵循这些原则和实践可以帮助您编写更具扩展性的Java类,从而更容易地适应未来的需求变化。