本文目录导读:

- 工厂模式(Factory Pattern)
- 单例模式(Singleton Pattern)
- 观察者模式(Observer Pattern)
- 策略模式(Strategy Pattern)
- 适配器模式(Adapter Pattern)
- 装饰器模式(Decorator Pattern)
- 构建器模式(Builder Pattern)
- 责任链模式(Chain of Responsibility)
我来为你提供几个Java设计模式的实践案例,每个都包含具体的代码示例和应用场景。
工厂模式(Factory Pattern)
场景:支付系统
// 支付接口
public interface Payment {
void pay(double amount);
}
// 具体支付方式
public class Alipay implements Payment {
@Override
public void pay(double amount) {
System.out.println("使用支付宝支付:" + amount + "元");
}
}
public class WechatPay implements Payment {
@Override
public void pay(double amount) {
System.out.println("使用微信支付:" + amount + "元");
}
}
// 工厂类
public class PaymentFactory {
public static Payment createPayment(String type) {
switch (type) {
case "alipay":
return new Alipay();
case "wechat":
return new WechatPay();
default:
throw new IllegalArgumentException("不支持的支付方式");
}
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
Payment payment = PaymentFactory.createPayment("alipay");
payment.pay(100.0);
}
}
单例模式(Singleton Pattern)
场景:数据库连接池
public class DatabaseConnectionPool {
// 使用volatile确保多线程下的可见性
private static volatile DatabaseConnectionPool instance;
private List<Connection> connections;
private DatabaseConnectionPool() {
// 私有构造函数
connections = new ArrayList<>();
// 初始化连接...
}
// 双重检查锁定
public static DatabaseConnectionPool getInstance() {
if (instance == null) {
synchronized (DatabaseConnectionPool.class) {
if (instance == null) {
instance = new DatabaseConnectionPool();
}
}
}
return instance;
}
public Connection getConnection() {
// 获取连接逻辑
return connections.remove(0);
}
}
观察者模式(Observer Pattern)
场景:天气预警系统
import java.util.ArrayList;
import java.util.List;
// 观察者接口
interface Observer {
void update(String weatherData);
}
// 被观察者(主题)
class WeatherStation {
private List<Observer> observers = new ArrayList<>();
private String weatherData;
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void setWeatherData(String data) {
this.weatherData = data;
notifyObservers();
}
private void notifyObservers() {
for (Observer observer : observers) {
observer.update(weatherData);
}
}
}
// 具体观察者:气象台
class MeteorologicalBureau implements Observer {
private String name;
public MeteorologicalBureau(String name) {
this.name = name;
}
@Override
public void update(String weatherData) {
System.out.println(name + " 收到天气预报:" + weatherData);
}
}
// 使用示例
public class WeatherSystem {
public static void main(String[] args) {
WeatherStation station = new WeatherStation();
MeteorologicalBureau beijing = new MeteorologicalBureau("北京气象台");
MeteorologicalBureau shanghai = new MeteorologicalBureau("上海气象台");
station.addObserver(beijing);
station.addObserver(shanghai);
station.setWeatherData("晴,25℃");
}
}
策略模式(Strategy Pattern)
场景:商品促销系统
// 策略接口
interface DiscountStrategy {
double calculateDiscount(double price);
}
// 具体策略:无折扣
class NoDiscount implements DiscountStrategy {
@Override
public double calculateDiscount(double price) {
return price;
}
}
// 具体策略:7折
class SevenFoldDiscount implements DiscountStrategy {
@Override
public double calculateDiscount(double price) {
return price * 0.7;
}
}
// 具体策略:满100减20
class FullReductionDiscount implements DiscountStrategy {
@Override
public double calculateDiscount(double price) {
if (price >= 100) {
return price - 20;
}
return price;
}
}
// 使用策略的上下文类
class CheckoutService {
private DiscountStrategy discountStrategy;
public CheckoutService(DiscountStrategy discountStrategy) {
this.discountStrategy = discountStrategy;
}
public double getFinalPrice(double originalPrice) {
return discountStrategy.calculateDiscount(originalPrice);
}
public void setDiscountStrategy(DiscountStrategy strategy) {
this.discountStrategy = strategy;
}
}
// 使用示例
public class ShoppingCart {
public static void main(String[] args) {
double originalPrice = 150.0;
CheckoutService checkout = new CheckoutService(new NoDiscount());
System.out.println("无折扣价格:" + checkout.getFinalPrice(originalPrice));
checkout.setDiscountStrategy(new SevenFoldDiscount());
System.out.println("7折价格:" + checkout.getFinalPrice(originalPrice));
checkout.setDiscountStrategy(new FullReductionDiscount());
System.out.println("满减价格:" + checkout.getFinalPrice(originalPrice));
}
}
适配器模式(Adapter Pattern)
场景:不同接口的对接
// 目标接口
interface JsonParser {
String parseToJson(String xmlData);
}
// 已有的XML解析器
class XmlParser {
public String parseXmlToObj(String xml) {
return "Object from XML: " + xml;
}
}
// 适配器类
class XmlToJsonAdapter implements JsonParser {
private XmlParser xmlParser;
public XmlToJsonAdapter(XmlParser xmlParser) {
this.xmlParser = xmlParser;
}
@Override
public String parseToJson(String xmlData) {
// 将XML数据转换为对象,然后再转成JSON格式
String object = xmlParser.parseXmlToObj(xmlData);
return "{\"data\":\"" + object + "\"}";
}
}
// 使用示例
public class DataSystem {
public static void main(String[] args) {
XmlParser xmlParser = new XmlParser();
JsonParser adapter = new XmlToJsonAdapter(xmlParser);
String xmlData = "<user>Java</user>";
String jsonData = adapter.parseToJson(xmlData);
System.out.println("转换结果:" + jsonData);
}
}
装饰器模式(Decorator Pattern)
场景:咖啡店
// 基础接口
interface Coffee {
double getCost();
String getDescription();
}
// 具体组件:基础咖啡
class SimpleCoffee implements Coffee {
@Override
public double getCost() {
return 10.0;
}
@Override
public String getDescription() {
return "基础咖啡";
}
}
// 装饰器抽象类
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee;
public CoffeeDecorator(Coffee coffee) {
this.decoratedCoffee = coffee;
}
@Override
public double getCost() {
return decoratedCoffee.getCost();
}
@Override
public String getDescription() {
return decoratedCoffee.getDescription();
}
}
// 具体装饰器:加牛奶
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) {
super(coffee);
}
@Override
public double getCost() {
return super.getCost() + 5.0;
}
@Override
public String getDescription() {
return super.getDescription() + ",加牛奶";
}
}
// 具体装饰器:加糖
class SugarDecorator extends CoffeeDecorator {
public SugarDecorator(Coffee coffee) {
super(coffee);
}
@Override
public double getCost() {
return super.getCost() + 2.0;
}
@Override
public String getDescription() {
return super.getDescription() + ",加糖";
}
}
// 使用示例
public class CoffeeShop {
public static void main(String[] args) {
Coffee coffee = new SimpleCoffee();
System.out.println(coffee.getDescription() + " - " + coffee.getCost() + "元");
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
System.out.println(coffee.getDescription() + " - " + coffee.getCost() + "元");
}
}
构建器模式(Builder Pattern)
场景:创建复杂对象
public class User {
// 必填字段
private final String name;
private final int age;
// 可选字段
private final String email;
private final String phone;
private User(UserBuilder builder) {
this.name = builder.name;
this.age = builder.age;
this.email = builder.email;
this.phone = builder.phone;
}
// 静态内部类Builder
public static class UserBuilder {
private final String name;
private final int age;
private String email;
private String phone;
public UserBuilder(String name, int age) {
this.name = name;
this.age = age;
}
public UserBuilder email(String email) {
this.email = email;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public User build() {
return new User(this);
}
}
// Getter方法...
public String getName() { return name; }
public int getAge() { return age; }
public String getEmail() { return email; }
public String getPhone() { return phone; }
}
// 使用示例
public class UserService {
public static void main(String[] args) {
User user = new User.UserBuilder("张三", 25)
.email("zhangsan@example.com")
.phone("13800138000")
.build();
System.out.println("用户信息:" + user.getName() + ", " + user.getAge() +
", " + user.getEmail() + ", " + user.getPhone());
}
}
责任链模式(Chain of Responsibility)
场景:请假审批系统
// 审批处理器抽象类
abstract class Approver {
protected Approver nextApprover;
public void setNextApprover(Approver next) {
this.nextApprover = next;
}
public abstract void approveRequest(int days);
}
// 具体处理器:主管
class Supervisor extends Approver {
@Override
public void approveRequest(int days) {
if (days <= 3) {
System.out.println("主管批准了" + days + "天的请假");
} else if (nextApprover != null) {
System.out.println("主管无权审批,转交上级");
nextApprover.approveRequest(days);
}
}
}
// 具体处理器:部门经理
class DepartmentManager extends Approver {
@Override
public void approveRequest(int days) {
if (days <= 7) {
System.out.println("部门经理批准了" + days + "天的请假");
} else if (nextApprover != null) {
System.out.println("部门经理无权审批,转交上级");
nextApprover.approveRequest(days);
}
}
}
// 具体处理器:总经理
class GeneralManager extends Approver {
@Override
public void approveRequest(int days) {
System.out.println("总经理批准了" + days + "天的请假");
}
}
// 使用示例
public class ApprovalSystem {
public static void main(String[] args) {
Approver supervisor = new Supervisor();
Approver manager = new DepartmentManager();
Approver generalManager = new GeneralManager();
// 构建责任链
supervisor.setNextApprover(manager);
manager.setNextApprover(generalManager);
// 测试不同天数的请假
supervisor.approveRequest(2);
supervisor.approveRequest(5);
supervisor.approveRequest(10);
}
}
这些设计模式的核心价值:
- 工厂模式:解耦对象创建和使用
- 单例模式:确保全局唯一,节省资源
- 观察者模式:实现事件驱动和松耦合
- 策略模式:算法封装和灵活切换
- 适配器模式:接口兼容和桥梁
- 装饰器模式:动态扩展功能
- 构建器模式:创建复杂对象,提高可读性
- 责任链模式:请求处理链,灵活分派
在实际项目中,通常会组合使用多个设计模式来解决问题,选择设计模式时要考虑:
- 是否有足够的灵活性需求
- 是否增加过度设计
- 是否符合开闭原则
- 团队的理解和维护成本
建议:从简单场景开始练习,逐步掌握每种模式的使用时机和优劣势。