常见设计模式及其应用

常见设计模式及其应用

设计模式是软件工程中的最佳实践,它可以帮助我们更有效地管理代码结构、提高可维护性和可扩展性。以下是一些常见的设计模式及其在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中的应用。掌握这些设计模式可以帮助开发者编写更灵活和可维护的代码。在实际开发中,根据场景选择合适的设计模式,可以大大提高代码质量和开发效率。

25 Java字符串常用方法

25 Java字符串常用方法

在Java中,字符串是由一系列字符组成的对象,String类提供了多种方法来操作字符串。以下是一些常用的字符串方法及其详细说明。

1. 创建字符串

可以通过以下方式创建字符串:

1
2
String str1 = "Hello, World!";
String str2 = new String("Hello, World!");

2. 字符串长度

使用length()方法可以获取字符串的长度:

1
2
String str = "Hello";
int length = str.length(); // length = 5

3. 字符串拼接

可以使用+运算符或concat()方法来拼接字符串:

1
2
3
4
String str1 = "Hello";
String str2 = "World";
String result1 = str1 + " " + str2; // "Hello World"
String result2 = str1.concat(" ").concat(str2); // "Hello World"

4. 字符串比较

使用equals()equalsIgnoreCase()方法比较字符串:

1
2
3
4
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2); // false
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // true

5. 字符串查找

indexOf()lastIndexOf()方法用于查找子字符串的位置:

1
2
3
String str = "Hello, World!";
int index = str.indexOf("World"); // index = 7
int lastIndex = str.lastIndexOf("o"); // lastIndex = 8

6. 字符串截取

使用substring()方法可以截取字符串:

1
2
3
String str = "Hello, World!";
String subStr1 = str.substring(0, 5); // "Hello"
String subStr2 = str.substring(7); // "World!"

7. 字符串替换

使用replace()方法来替换字符串中的某些字符或子串:

1
2
String str = "Hello, World!";
String newStr = str.replace("World", "Java"); // "Hello, Java!"

8. 字符串转大写和小写

使用toUpperCase()toLowerCase()方法可以转换字符串的大小写:

1
2
3
String str = "Hello, World!";
String upperStr = str.toUpperCase(); // "HELLO, WORLD!"
String lowerStr = str.toLowerCase(); // "hello, world!"

9. 字符串去除空白

使用trim()方法去除字符串两端的空白:

1
2
String str = "   Hello, World!   ";
String trimmedStr = str.trim(); // "Hello, World!"

10. 字符串分割

使用split()方法可以将字符串分割成数组,指定分隔符:

1
2
String str = "apple,banana,orange";
String[] fruits = str.split(","); // {"apple", "banana", "orange"}

11. 字符串连接

String.join()方法可以连接多个字符串:

1
String joinedStr = String.join("-", "Hello", "World"); // "Hello-World"

12. 字符串转换为字符数组

使用toCharArray()方法可以将字符串转换为字符数组:

1
2
String str = "Hello";
char[] charArray = str.toCharArray(); // {'H', 'e', 'l', 'l', 'o'}

总结

通过上面的方法,你可以完成许多针对字符串的常见操作。进一步掌握这些方法,将增强你在Java编程中的字符串处理能力。记得在实际开发中多加练习,以熟练掌握这些方法的用法。

单例、工厂、观察者模式

单例、工厂、观察者模式

1. 单例模式

1.1 概述

单例模式是一种创建型设计模式,确保一个类只有一个实例,并提供一个全局访问点。适用于需要控制资源的情况,比如配置类、连接池等。

1.2 关键实现

有多种实现单例模式的方法,下面是最常见的几种:

1.2.1 饿汉式单例

在类加载时就实例化对象,线程安全。

1
2
3
4
5
6
7
8
9
public class Singleton {
private static final Singleton INSTANCE = new Singleton();

private Singleton() {} // 私有构造函数

public static Singleton getInstance() {
return INSTANCE;
}
}

1.2.2 懒汉式单例

在第一次调用时才创建实例,需处理线程安全。

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

private Singleton() {}

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

1.3 总结

单例模式能有效控制实例化,保证唯一性。要注意线程安全及性能。


2. 工厂模式

2.1 概述

工厂模式是一种创建型设计模式,提供一个创建对象的接口,而不直接暴露对象的创建逻辑,允许子类决定实例化哪一个类。

2.2 工厂方法模式

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

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
// 产品接口
public interface Product {
void use();
}

// 具体产品
public class ConcreteProductA implements Product {
public void use() {
System.out.println("使用产品A");
}
}

public class ConcreteProductB implements Product {
public void use() {
System.out.println("使用产品B");
}
}

// 工厂接口
public interface ProductFactory {
Product createProduct();
}

// 具体工厂
public class ConcreteFactoryA implements ProductFactory {
public Product createProduct() {
return new ConcreteProductA();
}
}

public class ConcreteFactoryB implements ProductFactory {
public Product createProduct() {
return new ConcreteProductB();
}
}

2.3 总结

工厂模式帮助解耦,增加代码的扩展性。可以使用工厂方法模式来便于创建复杂对象。


3. 观察者模式

3.1 概述

观察者模式是一种行为型设计模式,定义了一种一对多的依赖关系,允许多个观察者同时监听某一个主题对象。主题对象在状态发生变化时通知所有观察者。

3.2 实现步骤

  1. 定义主题接口
  2. 定义观察者接口
  3. 实现具体主题和观察者
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// 主题接口
public interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}

// 观察者接口
public interface Observer {
void update(String message);
}

// 具体主题
import java.util.ArrayList;
import java.util.List;

public class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
private String state;

public void setState(String state) {
this.state = state;
notifyObservers();
}

public String getState() {
return state;
}

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

public void removeObserver(Observer observer) {
observers.remove(observer);
}

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

// 具体观察者
public class ConcreteObserver implements Observer {
private String name;

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

public void update(String message) {
System.out.println(name + " 收到消息: " + message);
}
}

3.3 使用示例

1
2
3
4
5
6
7
8
9
10
11
12
public class Main {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
ConcreteObserver observer1 = new ConcreteObserver("观察者1");
ConcreteObserver observer2 = new ConcreteObserver("观察者2");

subject.registerObserver(observer1);
subject.registerObserver(observer2);

subject.setState("状态改变了!");
}
}

3.4 总结

观察者模式适用于事件驱动的设计架构,如 GUI 和消息系统。实现了低耦合,可以灵活添加和移除观察者。