单例模式确保一个类只有一个实例,通常用于管理共享资源,如配置、缓存、线程池等。
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;
}
}
工厂模式用于封装对象的创建逻辑,特别是当类实例化过程复杂时,可以降低耦合度。
public class PaymentFactory {
public static Payment createPayment(String type) {
switch (type) {
case "AliPay":
return new AliPay();
case "WeChatPay":
return new WeChatPay();
default:
throw new IllegalArgumentException("Unknown payment type");
}
}
}
策略模式将不同算法封装为独立类,并允许在运行时选择不同的策略。
public interface PromotionStrategy {
void applyPromotion();
}
public class DiscountStrategy implements PromotionStrategy {
@Override
public void applyPromotion() {
System.out.println("Applying discount...");
}
}
public class PromotionContext {
private PromotionStrategy strategy;
public PromotionContext(PromotionStrategy strategy) {
this.strategy = strategy;
}
public void executePromotion() {
strategy.applyPromotion();
}
}
代理模式通过代理对象控制对目标对象的访问,常用于权限控制、日志记录等场景。
public interface Service {
void execute();
}
public class RealService implements Service {
@Override
public void execute() {
System.out.println("Executing real service...");
}
}
public class ServiceProxy implements Service {
private RealService realService;
@Override
public void execute() {
System.out.println("Checking permissions...");
if (realService == null) {
realService = new RealService();
}
realService.execute();
}
}
观察者模式定义一对多的依赖,当一个对象状态变化时,所有依赖它的对象都会收到通知。
public interface Observer {
void update(String message);
}
public class User implements Observer {
private String name;
public User(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + " received message: " + message);
}
}
public class Weibo {
private List<Observer> observers = new ArrayList<>();
public void follow(Observer observer) {
observers.add(observer);
}
public void post(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
装饰器模式在不改变原始类的基础上,动态扩展其功能。
public interface Coffee {
String getDescription();
double getCost();
}
public class SimpleCoffee implements Coffee {
@Override
public String getDescription() {
return "Simple Coffee";
}
@Override
public double getCost() {
return 5.0;
}
}
public class MilkDecorator implements Coffee {
private Coffee coffee;
public MilkDecorator(Coffee coffee) {
this.coffee = coffee;
}
@Override
public String getDescription() {
return coffee.getDescription() + ", Milk";
}
@Override
public double getCost() {
return coffee.getCost() + 1.5;
}
}
模板方法模式定义一个算法的骨架,把具体的实现留给子类。
public abstract class Task {
public final void execute() {
init();
doWork();
cleanup();
}
protected abstract void init();
protected abstract void doWork();
protected void cleanup() {
System.out.println("Default cleanup...");
}
}
public class DataProcessingTask extends Task {
@Override
protected void init() {
System.out.println("Initializing data...");
}
@Override
protected void doWork() {
System.out.println("Processing data...");
}
}
建造者模式用于创建复杂对象,特别是当对象有多个可选参数时。
public class HttpRequest {
private String method;
private String url;
private String body;
private HttpRequest(Builder builder) {
this.method = builder.method;
this.url = builder.url;
this.body = builder.body;
}
public static class Builder {
private String method;
private String url;
private String body;
public Builder method(String method) {
this.method = method;
return this;
}
public Builder url(String url) {
this.url = url;
return this;
}
public Builder body(String body) {
this.body = body;
return this;
}
public HttpRequest build() {
return new HttpRequest(this);
}
}
}
在软件开发的广阔天地中,设计模式不仅是解决特定问题的模板,更是提升代码质量、可维护性和可扩展性的有力工具。通过本文的探讨,我们深入了解了8种设计模式:单例模式、工厂模式、策略模式、代理模式、观察者模式、装饰器模式、模板方法模式和建造者模式。每种模式都以其独特的方式,帮助我们应对软件开发中的复杂性,提供了一种清晰、结构化的方法来构建灵活且健壮的系统。
在JDK和Spring框架中,设计模式的应用无处不在,这不仅证明了它们的有效性,也为我们在实际项目中应用这些模式提供了参考。例如,Spring框架中的单例模式管理着Bean的生命周期,工厂模式在创建Bean时发挥着重要作用,而策略模式则在动态选择数据库查询策略时大显身手。
设计模式的学习是一个持续的过程,它要求我们不断地实践、反思和改进。希望本文能够作为您学习设计模式旅程中的一个起点,激发您在实际项目中探索和应用这些强大工具的热情。如果您有任何疑问、见解或经验分享,欢迎在评论区交流,让我们共同进步。。