在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類,從而更容易地適應未來的需求變化。