java设计模式


java 设计模式 


Java设计模式是面向对象编程中解决常见问题的经典解决方案。设计模式通常分为三大类:

## 创建型模式 (Creational Patterns)
负责对象的创建过程

### 1. 单例模式 (Singleton)
确保一个类只有一个实例,并提供全局访问点。

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

### 2. 工厂模式 (Factory)
通过工厂类创建对象,而不是直接new。

```java
public abstract class Animal {
    public abstract void makeSound();
}

public class Dog extends Animal {
    public void makeSound() { System.out.println("汪汪"); }
}

public class Cat extends Animal {
    public void makeSound() { System.out.println("喵喵"); }
}

public class AnimalFactory {
    public static Animal createAnimal(String type) {
        switch (type) {
            case "dog": return new Dog();
            case "cat": return new Cat();
            default: throw new IllegalArgumentException("未知动物类型");
        }
    }
}
```

### 3. 建造者模式 (Builder)
构建复杂对象的过程和表示分离。

```java
public class Computer {
    private String cpu;
    private String memory;
    private String storage;
    
    private Computer(Builder builder) {
        this.cpu = builder.cpu;
        this.memory = builder.memory;
        this.storage = builder.storage;
    }
    
    public static class Builder {
        private String cpu;
        private String memory;
        private String storage;
        
        public Builder setCpu(String cpu) {
            this.cpu = cpu;
            return this;
        }
        
        public Builder setMemory(String memory) {
            this.memory = memory;
            return this;
        }
        
        public Builder setStorage(String storage) {
            this.storage = storage;
            return this;
        }
        
        public Computer build() {
            return new Computer(this);
        }
    }
}
```

## 结构型模式 (Structural Patterns)
处理类和对象的组合

### 1. 适配器模式 (Adapter)
让不兼容的接口能够一起工作。

```java
// 目标接口
public interface Target {
    void request();
}

// 需要适配的类
public class Adaptee {
    public void specificRequest() {
        System.out.println("特殊请求");
    }
}

// 适配器
public class Adapter implements Target {
    private Adaptee adaptee;
    
    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
    
    public void request() {
        adaptee.specificRequest();
    }
}
```

### 2. 装饰器模式 (Decorator)
动态地给对象添加功能。

```java
public abstract class Beverage {
    protected String description = "未知饮料";
    
    public String getDescription() {
        return description;
    }
    
    public abstract double cost();
}

public class Coffee extends Beverage {
    public Coffee() {
        description = "咖啡";
    }
    
    public double cost() {
        return 1.99;
    }
}

public abstract class CondimentDecorator extends Beverage {
    public abstract String getDescription();
}

public class Milk extends CondimentDecorator {
    Beverage beverage;
    
    public Milk(Beverage beverage) {
        this.beverage = beverage;
    }
    
    public String getDescription() {
        return beverage.getDescription() + ", 牛奶";
    }
    
    public double cost() {
        return 0.10 + beverage.cost();
    }
}
```

## 行为型模式 (Behavioral Patterns)
关注对象间的通信和职责分配

### 1. 观察者模式 (Observer)
定义对象间一对多的依赖关系。

```java
import java.util.*;

public interface Observer {
    void update(String message);
}

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

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);
    }
}
```

### 2. 策略模式 (Strategy) 
定义算法族,分别封装起来,让它们之间可以互相替换。

```java
public interface PaymentStrategy {
    void pay(double amount);
}

public class CreditCardPayment implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("使用信用卡支付: " + amount + "元");
    }
}

public class AlipayPayment implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("使用支付宝支付: " + amount + "元");
    }
}

public class PaymentContext {
    private PaymentStrategy strategy;
    
    public void setPaymentStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }
    
    public void executePayment(double amount) {
        strategy.pay(amount);
    }
}
```

## 设计模式的优势

1. **代码重用性** - 提供经过验证的解决方案
2. **可维护性** - 使代码结构更清晰
3. **沟通效率** - 开发团队有共同的设计语言
4. **最佳实践** - 避免常见的设计错误

## 使用建议

- 不要过度使用设计模式
- 根据实际需求选择合适的模式
- 理解模式的本质,而不是死记硬背
- 在重构中逐步引入设计模式

你对哪个特定的设计模式感兴趣?我可以提供更详细的解释和示例。

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

```java
public abstract class Animal {
    public abstract void makeSound();
}

public class Dog extends Animal {
    public void makeSound() { System.out.println("汪汪"); }
}

public class Cat extends Animal {
    public void makeSound() { System.out.println("喵喵"); }
}

public class AnimalFactory {
    public static Animal createAnimal(String type) {
        switch (type) {
            case "dog": return new Dog();
            case "cat": return new Cat();
            default: throw new IllegalArgumentException("未知动物类型");
        }
    }
}
```

```java
public class Computer {
    private String cpu;
    private String memory;
    private String storage;
    
    private Computer(Builder builder) {
        this.cpu = builder.cpu;
        this.memory = builder.memory;
        this.storage = builder.storage;
    }
    
    public static class Builder {
        private String cpu;
        private String memory;
        private String storage;
        
        public Builder setCpu(String cpu) {
            this.cpu = cpu;
            return this;
        }
        
        public Builder setMemory(String memory) {
            this.memory = memory;
            return this;
        }
        
        public Builder setStorage(String storage) {
            this.storage = storage;
            return this;
        }
        
        public Computer build() {
            return new Computer(this);
        }
    }
}
```

```java
// 目标接口
public interface Target {
    void request();
}

// 需要适配的类
public class Adaptee {
    public void specificRequest() {
        System.out.println("特殊请求");
    }
}

// 适配器
public class Adapter implements Target {
    private Adaptee adaptee;
    
    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
    
    public void request() {
        adaptee.specificRequest();
    }
}
```

```java
public abstract class Beverage {
    protected String description = "未知饮料";
    
    public String getDescription() {
        return description;
    }
    
    public abstract double cost();
}

public class Coffee extends Beverage {
    public Coffee() {
        description = "咖啡";
    }
    
    public double cost() {
        return 1.99;
    }
}

public abstract class CondimentDecorator extends Beverage {
    public abstract String getDescription();
}

public class Milk extends CondimentDecorator {
    Beverage beverage;
    
    public Milk(Beverage beverage) {
        this.beverage = beverage;
    }
    
    public String getDescription() {
        return beverage.getDescription() + ", 牛奶";
    }
    
    public double cost() {
        return 0.10 + beverage.cost();
    }
}
```

```java
import java.util.*;

public interface Observer {
    void update(String message);
}

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

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);
    }
}
```

```java
public interface PaymentStrategy {
    void pay(double amount);
}

public class CreditCardPayment implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("使用信用卡支付: " + amount + "元");
    }
}

public class AlipayPayment implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("使用支付宝支付: " + amount + "元");
    }
}

public class PaymentContext {
    private PaymentStrategy strategy;
    
    public void setPaymentStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }
    
    public void executePayment(double amount) {
        strategy.pay(amount);
    }
}
```


posted @ 2025-06-08 09:39  予真  阅读(19)  评论(0)    收藏  举报