Java 设计模式是用于解决软件设计问题的经典解决方案。它们提供了一种可重用的方法,以应对不断变化的需求和问题。以下是几种常见的 Java 设计模式,可以帮助应对变化:
// 策略接口
public interface Strategy {
int doOperation(int a, int b);
}
// 具体策略类
public class AddStrategy implements Strategy {
@Override
public int doOperation(int a, int b) {
return a + b;
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Strategy strategy = new AddStrategy();
int result = strategy.doOperation(1, 2);
System.out.println("Result: " + result);
}
}
// 主题接口
public interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
// 具体主题类
public class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
public void changeState() {
notifyObservers();
}
}
// 观察者接口
public interface Observer {
void update();
}
// 具体观察者类
public class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
@Override
public void update() {
System.out.println(name + " has been notified.");
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
Observer observer1 = new ConcreteObserver("Observer 1");
Observer observer2 = new ConcreteObserver("Observer 2");
subject.registerObserver(observer1);
subject.registerObserver(observer2);
subject.changeState();
}
}
// 抽象类
public abstract class AbstractTemplateMethod {
public final void templateMethod() {
step1();
step2();
step3();
}
protected abstract void step1();
protected abstract void step2();
protected void step3() {
System.out.println("Step 3");
}
}
// 具体子类
public class ConcreteTemplateMethod extends AbstractTemplateMethod {
@Override
protected void step1() {
System.out.println("ConcreteTemplateMethod step 1");
}
@Override
protected void step2() {
System.out.println("ConcreteTemplateMethod step 2");
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
AbstractTemplateMethod templateMethod = new ConcreteTemplateMethod();
templateMethod.templateMethod();
}
}
通过使用这些设计模式,我们可以更好地应对 Java 项目中的变化,提高代码的可维护性和可扩展性。