Java设计模式实践

设计模式是软件开发中解决常见问题的最佳实践,下面列出几种常用设计模式及其基础使用方法示例。


1. 单例模式(Singleton)

确保一个类只有一个实例,提供全局访问点。

1
2
3
4
5
6
7
8
9
10
11
12
public class Singleton {
private static Singleton instance;

private Singleton() {}

public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

2. 工厂模式(Factory Method)

定义一个创建对象的接口,让子类决定实例化哪一个类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
interface Product {
void use();
}

class ConcreteProductA implements Product {
public void use() {
System.out.println("Using Product A");
}
}

class ConcreteProductB implements Product {
public void use() {
System.out.println("Using Product B");
}
}

abstract class Creator {
abstract Product factoryMethod();

public void someOperation() {
Product product = factoryMethod();
product.use();
}
}

class ConcreteCreatorA extends Creator {
Product factoryMethod() {
return new ConcreteProductA();
}
}

class ConcreteCreatorB extends Creator {
Product factoryMethod() {
return new ConcreteProductB();
}
}

3. 抽象工厂模式(Abstract Factory)

创建一组相关或相互依赖的对象接口,而无需指定它们具体的类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}

class WinFactory implements GUIFactory {
public Button createButton() { return new WinButton(); }
public Checkbox createCheckbox() { return new WinCheckbox(); }
}

class MacFactory implements GUIFactory {
public Button createButton() { return new MacButton(); }
public Checkbox createCheckbox() { return new MacCheckbox(); }
}

interface Button { void paint(); }
class WinButton implements Button { public void paint() { System.out.println("Windows Button"); } }
class MacButton implements Button { public void paint() { System.out.println("Mac Button"); } }

interface Checkbox { void paint(); }
class WinCheckbox implements Checkbox { public void paint() { System.out.println("Windows Checkbox"); } }
class MacCheckbox implements Checkbox { public void paint() { System.out.println("Mac Checkbox"); } }

4. 代理模式(Proxy)

为其他对象提供一个代理以控制对这个对象的访问。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface Subject {
void request();
}

class RealSubject implements Subject {
public void request() {
System.out.println("RealSubject: Handling request.");
}
}

class Proxy implements Subject {
private RealSubject realSubject;

public void request() {
if (realSubject == null) {
realSubject = new RealSubject();
}
System.out.println("Proxy: Logging request.");
realSubject.request();
}
}

5. 观察者模式(Observer)

定义对象间一对多的依赖,当一个对象状态改变时,所有依赖它的对象都会收到通知并自动更新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;

interface Observer {
void update(String message);
}

class ConcreteObserver implements Observer {
private String name;
ConcreteObserver(String name) { this.name = name; }
public void update(String message) {
System.out.println(name + " received: " + message);
}
}

class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer o) { observers.add(o); }
public void removeObserver(Observer o) { observers.remove(o); }
public void notifyObservers(String msg) {
for (Observer o : observers) o.update(msg);
}
}

6. 装饰器模式(Decorator)

动态地给对象添加额外职责,增强功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
interface Component {
void operation();
}

class ConcreteComponent implements Component {
public void operation() {
System.out.println("ConcreteComponent operation");
}
}

class Decorator implements Component {
protected Component component;
public Decorator(Component c) { this.component = c; }
public void operation() {
component.operation();
}
}

class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component c) {
super(c);
}
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
System.out.println("ConcreteDecorator added behavior");
}
}

7. 策略模式(Strategy)

定义一系列算法,把它们封装起来,使它们可以互换。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface Strategy {
int doOperation(int a, int b);
}

class OperationAdd implements Strategy {
public int doOperation(int a, int b) { return a + b; }
}

class OperationMultiply implements Strategy {
public int doOperation(int a, int b) { return a * b; }
}

class Context {
private Strategy strategy;
public Context(Strategy s) { this.strategy = s; }
public int executeStrategy(int a, int b) {
return strategy.doOperation(a, b);
}
}

8. 模板方法模式(Template Method)

定义一个操作中的算法骨架,而将一些步骤延迟到子类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
abstract class AbstractClass {
public final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
concreteOperation();
}
protected abstract void primitiveOperation1();
protected abstract void primitiveOperation2();
private void concreteOperation() {
System.out.println("Common operation");
}
}

class ConcreteClass extends AbstractClass {
protected void primitiveOperation1() {
System.out.println("ConcreteClass Operation1");
}
protected void primitiveOperation2() {
System.out.println("ConcreteClass Operation2");
}
}

9. 责任链模式(Chain of Responsibility)

避免请求发送者与接收者耦合,将多个对象连成一条链,并沿着链传递请求。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
abstract class Handler {
protected Handler successor;
public void setSuccessor(Handler successor) {
this.successor = successor;
}
public abstract void handleRequest(int request);
}

class ConcreteHandler1 extends Handler {
public void handleRequest(int request) {
if (request < 10) {
System.out.println("Handler1 handled request " + request);
} else if (successor != null) {
successor.handleRequest(request);
}
}
}

class ConcreteHandler2 extends Handler {
public void handleRequest(int request) {
if (request >= 10) {
System.out.println("Handler2 handled request " + request);
} else if (successor != null) {
successor.handleRequest(request);
}
}
}

10. 迭代器模式(Iterator)

提供一种方法访问一个容器对象中各个元素,而又不暴露该对象的内部表示。

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.*;

class MyCollection {
private List<String> items = new ArrayList<>();

public void add(String item) {
items.add(item);
}

public Iterator<String> iterator() {
return items.iterator();
}
}