Java設(shè)計(jì)模式是解決軟件設(shè)計(jì)中常見問題的優(yōu)秀解決方案。它們提供了一種可重用的、經(jīng)過驗(yàn)證的模板,可以幫助開發(fā)者更有效地解決復(fù)雜問題。以下是幾種常用的Java設(shè)計(jì)模式及其解決復(fù)雜問題的方法:
單例模式(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));
}
}
通過這些設(shè)計(jì)模式,Java開發(fā)者可以更靈活地應(yīng)對(duì)復(fù)雜的設(shè)計(jì)問題,提高代碼的可維護(hù)性和可擴(kuò)展性。