Java設計模式是解決軟件設計中常見問題的優秀解決方案。它們提供了一種可重用的、經過驗證的模板,可以幫助開發者更有效地解決復雜問題。以下是幾種常用的Java設計模式及其解決復雜問題的方法:
單例模式(Singleton Pattern):
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
工廠模式(Factory Pattern):
public interface Product {
void use();
}
public class ConcreteProduct implements Product {
@Override
public void use() {
System.out.println("Using ConcreteProduct");
}
}
public class Factory {
public static Product createProduct() {
return new ConcreteProduct();
}
}
public class Client {
public static void main(String[] args) {
Product product = Factory.createProduct();
product.use();
}
}
觀察者模式(Observer Pattern):
public interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}
public interface Observer {
void update();
}
public class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
public void changeState() {
notifyObservers();
}
}
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();
}
}
策略模式(Strategy Pattern):
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 SubtractStrategy implements Strategy {
@Override
public int doOperation(int a, int b) {
return a - b;
}
}
public class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public int executeStrategy(int a, int b) {
return strategy.doOperation(a, b);
}
}
public class Client {
public static void main(String[] args) {
Context context = new Context();
context.setStrategy(new AddStrategy());
System.out.println("Result: " + context.executeStrategy(10, 5));
context.setStrategy(new SubtractStrategy());
System.out.println("Result: " + context.executeStrategy(10, 5));
}
}
通過這些設計模式,Java開發者可以更靈活地應對復雜的設計問題,提高代碼的可維護性和可擴展性。