Java 設計模式是用于解決軟件設計問題的經(jīng)典解決方案。它們提供了一種可重用的方法,以應對不斷變化的需求和問題。以下是幾種常見的 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 項目中的變化,提高代碼的可維護性和可擴展性。