常见设计模式及其应用

常见设计模式及其应用

设计模式是软件工程中的最佳实践,它可以帮助我们更有效地管理代码结构、提高可维护性和可扩展性。以下是一些常见的设计模式及其在Java中的应用。

1. 单例模式(Singleton)

定义

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

应用场景

需要控制实例数量的场景,比如配置文件管理、线程池等。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Singleton {
// 静态变量保存唯一实例
private static Singleton instance;

// 构造器私有化
private Singleton() {}

// 提供一个全局的静态方法返回实例
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

2. 工厂模式(Factory)

定义

工厂模式通过定义一个接口或抽象类,并由子类实现这个接口,以此来创建对象。分为简单工厂、工厂方法和抽象工厂三种类型。

应用场景

需要根据不同条件创建不同对象的场景。

示例代码

简单工厂

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
public class ShapeFactory {
public static Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}

interface Shape {
void draw();
}

class Circle implements Shape {
public void draw() {
System.out.println("Drawing a Circle");
}
}

class Square implements Shape {
public void draw() {
System.out.println("Drawing a Square");
}
}

// 使用工厂
Shape shape = ShapeFactory.getShape("CIRCLE");
shape.draw();

3. 观察者模式(Observer)

定义

观察者模式定义了一种一对多的依赖关系,让多个观察者对象能够同时监听某一个主题对象。

应用场景

实现事件系统时,多个组件需要对某个事件作出反应。

示例代码

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
37
38
39
40
41
import java.util.ArrayList;
import java.util.List;

interface Observer {
void update(String message);
}

class ConcreteObserver implements Observer {
private String name;

public ConcreteObserver(String name) {
this.name = name;
}

public void update(String message) {
System.out.println(name + " received message: " + message);
}
}

class Subject {
private List<Observer> observers = new ArrayList<>();

public void addObserver(Observer observer) {
observers.add(observer);
}

public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}

// 使用观察者模式
Subject subject = new Subject();
ConcreteObserver observer1 = new ConcreteObserver("Observer1");
ConcreteObserver observer2 = new ConcreteObserver("Observer2");

subject.addObserver(observer1);
subject.addObserver(observer2);
subject.notifyObservers("Hello Observers!");

4. 策略模式(Strategy)

定义

策略模式定义一系列算法,并将每一个算法封装起来,使它们可以互相替换。策略模式使得算法的变化独立于使用它的客户。

应用场景

需要在运行时选择算法或行为的场景。

示例代码

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
interface Strategy {
int doOperation(int num1, int num2);
}

class Addition implements Strategy {
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}

class Subtraction implements Strategy {
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}

class Context {
private Strategy strategy;

public Context(Strategy strategy) {
this.strategy = strategy;
}

public int executeStrategy(int num1, int num2) {
return strategy.doOperation(num1, num2);
}
}

// 使用策略模式
Context context = new Context(new Addition());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

context = new Context(new Subtraction());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));

5. 装饰者模式(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
31
32
33
34
35
36
37
interface Coffee {
String getDescription();
double cost();
}

class SimpleCoffee implements Coffee {
public String getDescription() {
return "Simple Coffee";
}

public double cost() {
return 5.0;
}
}

class MilkDecorator implements Coffee {
private Coffee coffee;

public MilkDecorator(Coffee coffee) {
this.coffee = coffee;
}

public String getDescription() {
return coffee.getDescription() + ", with Milk";
}

public double cost() {
return coffee.cost() + 1.5;
}
}

// 使用装饰者模式
Coffee coffee = new SimpleCoffee();
System.out.println(coffee.getDescription() + " $" + coffee.cost());

coffee = new MilkDecorator(coffee);
System.out.println(coffee.getDescription() + " $" + coffee.cost());

结语

以上是一些常见的设计模式及其在Java中的应用。掌握这些设计模式可以帮助开发者编写更灵活和可维护的代码。在实际开发中,根据场景选择合适的设计模式,可以大大提高代码质量和开发效率。

常见设计模式及其应用

https://zglg.work/java-one/25/

作者

AI教程网

发布于

2024-08-08

更新于

2024-08-10

许可协议