在软件开发领域,设计模式是经过时间验证的解决方案,它们可以帮助开发者解决常见问题,提高代码质量,并提升软件架构的思维能力。Java作为一种广泛使用的编程语言,其设计模式尤为重要。本文将深入探讨Java...
在软件开发领域,设计模式是经过时间验证的解决方案,它们可以帮助开发者解决常见问题,提高代码质量,并提升软件架构的思维能力。Java作为一种广泛使用的编程语言,其设计模式尤为重要。本文将深入探讨Java中的12大经典设计模式,帮助读者掌握其核心思想,提升代码质量和架构思维。
单例模式确保一个类只有一个实例,并提供一个全局访问点。适用于共享资源场景,如数据库连接池、日志记录器等。
public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; }
}public class Singleton { private static Singleton instance; private Singleton() {} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }
}工厂方法模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。适用于创建具有共同接口的类族。
public interface Factory { T create(Class clazz);
}
public class ConcreteFactory implements Factory { @Override public T create(Class clazz) { if (clazz.equals(ConcreteProductA.class)) { return (T) new ConcreteProductA(); } else if (clazz.equals(ConcreteProductB.class)) { return (T) new ConcreteProductB(); } return null; }
} 抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
public interface AbstractFactory { ProductA createProductA(); ProductB createProductB();
}
public class ConcreteFactory1 implements AbstractFactory { @Override public ProductA createProductA() { return new ConcreteProductA1(); } @Override public ProductB createProductB() { return new ConcreteProductB1(); }
}建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
public class Builder { public void createPartA() {} public void createPartB() {} public Product getResult() { return new Product(this); }
}
public class Director { private Builder builder; public Director(Builder builder) { this.builder = builder; } public void construct() { builder.createPartA(); builder.createPartB(); }
}原型模式通过复制现有的实例来创建新的实例,实现对象的创建与表示分离。
public class Prototype implements Cloneable { public Prototype clone() { try { return (Prototype) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(); } }
}适配器模式将一个类的接口转换成客户期望的另一个接口,使原本接口不兼容的类可以一起工作。
public class Target { public void request() { System.out.println("Target request."); }
}
public class Adaptee { public void specificRequest() { System.out.println("Adaptee specificRequest."); }
}
public class Adapter extends Adaptee implements Target { @Override public void request() { specificRequest(); }
}桥接模式将抽象部分与实现部分分离,使它们都可以独立地变化。
public interface Abstraction { void operation();
}
public class RefinedAbstraction extends Abstraction { @Override public void operation() { // 实现细节 }
}
public class Implementor { public void operationImpl() { // 实现细节 }
}
public class ConcreteImplementorA extends Implementor { @Override public void operationImpl() { // 实现细节 }
}
public class ConcreteAbstraction extends RefinedAbstraction { private Implementor implementor; public ConcreteAbstraction(Implementor implementor) { this.implementor = implementor; } @Override public void operation() { implementor.operationImpl(); }
}组合模式将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
public interface Component { void operation();
}
public class Leaf implements Component { @Override public void operation() { // 实现细节 }
}
public class Composite implements Component { private List children = new ArrayList<>(); @Override public void operation() { for (Component child : children) { child.operation(); } } public void add(Component child) { children.add(child); }
} 装饰器模式动态地给一个对象添加一些额外的职责,而不改变其接口。
public interface Component { void operation();
}
public class ConcreteComponent implements Component { @Override public void operation() { // 实现细节 }
}
public class Decorator implements Component { private Component component; public Decorator(Component component) { this.component = component; } @Override public void operation() { component.operation(); // 添加额外职责 }
}观察者模式定义对象间的一对多依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。
public interface Observer { void update();
}
public class ConcreteObserver implements Observer { @Override public void update() { // 实现细节 }
}
public class Subject { private List observers = new ArrayList<>(); public void addObserver(Observer observer) { observers.add(observer); } public void notifyObservers() { for (Observer observer : observers) { observer.update(); } }
} 状态模式允许一个对象在其内部状态改变时改变它的行为。
public interface State { void handle();
}
public class ConcreteStateA implements State { @Override public void handle() { // 实现细节 }
}
public class Context { private State state; public void setState(State state) { this.state = state; } public void request() { state.handle(); }
}策略模式定义一系列算法,把它们一个个封装起来,并使它们可以相互替换。
public interface Strategy { void execute();
}
public class ConcreteStrategyA implements Strategy { @Override public void execute() { // 实现细节 }
}
public class Context { private Strategy strategy; public void setStrategy(Strategy strategy) { this.strategy = strategy; } public void executeStrategy() { strategy.execute(); }
}掌握这些经典设计模式,可以帮助开发者提高代码质量,提升软件架构思维。在实际项目中,灵活运用设计模式,可以降低代码复杂度,提高系统可维护性和可扩展性。