Java设计模式是为了解决软件开发中常见的问题而创建的一系列最佳实践。它们提供了一种在特定情境下解决问题的方法论,并且已经被广泛验证和应用。这些模式不是具体的代码,而是关于如何组织代码以达到某种目的的高层次描述。设计模式通常分为三大类:创建型模式、结构型模式和行为型模式。
一 创建型模式
这类模式主要处理对象的创建方式,目的是将系统与具体类解耦。
1. 单例模式 (Singleton Pattern)
确保一个类只有一个实例,并提供一个全局访问点。例如,数据库连接池或日志记录器。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2. 工厂方法模式 (Factory Method Pattern)
定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。
interface Product { void use(); }
class ConcreteProduct implements Product { public void use() {} }
abstract class Creator {
public final Product create(String type) {
Product product = factoryMethod(type);
// 准备、初始化等
return product;
}
protected abstract Product factoryMethod(String type);
}
class ConcreteCreator extends Creator {
protected Product factoryMethod(String type) {
if ("A".equals(type)) {
return new ConcreteProduct();
} else {
throw new IllegalArgumentException("Invalid product type");
}
}
}
3. 抽象工厂模式 (Abstract Factory Pattern)
提供一个接口来创建一系列相关或相互依赖的对象,而无需指定它们的具体类。
interface AbstractFactory {
ProductA createProductA();
ProductB createProductB();
}
class ConcreteFactory1 implements AbstractFactory {
public ProductA createProductA() { return new ConcreteProductA1(); }
public ProductB createProductB() { return new ConcreteProductB1(); }
}
// 其他产品和工厂实现...
4. 建造者模式 (Builder Pattern)
将复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
class Product {
// 复杂对象属性
}
interface Builder {
void buildPartA();
void buildPartB();
Product getResult();
}
class ConcreteBuilder implements Builder {
private Product product = new Product();
public void buildPartA() { /* 构建部分A */ }
public void buildPartB() { /* 构建部分B */ }
public Product getResult() { return product; }
}
class Director {
private Builder builder;
public Director(Builder builder) { this.builder = builder; }
public void construct() {
builder.buildPartA();
builder.buildPartB();
}
}
5. 原型模式 (Prototype Pattern)
通过复制现有实例来创建新实例,而不是通过构造函数创建。
interface Prototype {
Prototype clone();
}
class ConcretePrototype implements Prototype, Cloneable {
@Override
public Prototype clone() {
try {
return (ConcretePrototype) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
二 结构型模式
结构型模式关注于如何组合类和对象以形成更大的结构,同时保持结构的灵活性和高效性。
1. 适配器模式 (Adapter Pattern)
允许不兼容接口的对象能够一起工作。
interface Target {
void request();
}
class Adaptee {
void specificRequest() {}
}
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) { this.adaptee = adaptee; }
public void request() { adaptee.specificRequest(); }
}
2. 桥接模式 (Bridge Pattern)
将抽象部分与它的实现部分分离,使它们都可以独立地变化。
interface Implementor {
void operationImpl();
}
class ConcreteImplementorA implements Implementor {
public void operationImpl() { /* 实现细节 */ }
}
abstract class Abstraction {
protected Implementor implementor;
public void setImplementor(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation();
}
class RefinedAbstraction extends Abstraction {
public void operation() {
implementor.operationImpl();
}
}
3. 装饰器模式 (Decorator Pattern)
动态地给一个对象添加一些额外的职责。
interface Component {
void operation();
}
class ConcreteComponent implements Component {
public void operation() { /* 基本功能 */ }
}
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) { super(component); }
public void addedBehavior() { /* 额外的行为 */ }
public void operation() {
super.operation();
addedBehavior();
}
}
4. 外观模式 (Facade Pattern)
提供了一个统一的接口,用来访问子系统中的一群接口。
class Subsystem1 { public void operation1() {} }
class Subsystem2 { public void operation2() {} }
class Subsystem3 { public void operation3() {} }
class Facade {
private Subsystem1 subsystem1;
private Subsystem2 subsystem2;
private Subsystem3 subsystem3;
public Facade() {
subsystem1 = new Subsystem1();
subsystem2 = new Subsystem2();
subsystem3 = new Subsystem3();
}
public void operation() {
subsystem1.operation1();
subsystem2.operation2();
subsystem3.operation3();
}
}
5. 享元模式 (Flyweight Pattern)
用于减少创建对象的数量,以减少内存占用并提高性能。
interface Flyweight {
void operation(int extrinsicState);
}
class ConcreteFlyweight implements Flyweight {
private int intrinsicState;
public ConcreteFlyweight(int intrinsicState) {
this.intrinsicState = intrinsicState;
}
public void operation(int extrinsicState) {
System.out.println("Intrinsic State: " + intrinsicState + ", Extrinsic State: " + extrinsicState);
}
}
class FlyweightFactory {
private Map<Integer, ConcreteFlyweight> flyweights = new HashMap<>();
public Flyweight getFlyweight(int key) {
if (!flyweights.containsKey(key)) {
flyweights.put(key, new ConcreteFlyweight(key));
}
return flyweights.get(key);
}
}
6. 代理模式 (Proxy Pattern)
为其他对象提供一种代理以控制对这个对象的访问。
interface Subject {
void request();
}
class RealSubject implements Subject {
public void request() { /* 实际操作 */ }
}
class Proxy implements Subject {
private RealSubject realSubject;
public void request() {
if (realSubject == null) {
realSubject = new RealSubject();
}
preRequest();
realSubject.request();
postRequest();
}
private void preRequest() { /* 在请求前执行的操作 */ }
private void postRequest() { /* 在请求后执行的操作 */ }
}
7. 组合模式 (Composite Pattern)
允许你将对象组合成树形结构来表示"部分-整体"的层次结构。
interface Component {
void add(Component c);
void remove(Component c);
void display(int depth);
}
class Leaf implements Component {
public void add(Component c) { throw new UnsupportedOperationException(); }
public void remove(Component c) { throw new UnsupportedOperationException(); }
public void display(int depth) { for (int i = 0; i < depth; i++) { System.out.print("-"); } System.out.println("Leaf"); }
}
class Composite implements Component {
private List<Component> children = new ArrayList<>();
public void add(Component c) { children.add(c); }
public void remove(Component c) { children.remove(c); }
public void display(int depth) {
for (int i = 0; i < depth; i++) { System.out.print("-"); }
System.out.println("+ Composite");
for (Component child : children) {
child.display(depth + 1);
}
}
}
三 行为型模式
行为型模式涉及对象之间的通信和协作,以及分配责任和算法的方式。
1. 策略模式 (Strategy Pattern)
定义了一系列可互换的算法,并将每个算法封装起来,使得算法的变化独立于使用算法的客户。
interface Strategy {
int doOperation(int num1, int num2);
}
class OperationAdd 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);
}
}
2. 观察者模式 (Observer Pattern)
当一个对象的状态改变时,所有依赖它的对象都会收到通知并自动更新。
interface Observer {
void update(String message);
}
interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers(String message);
}
class ConcreteSubject implements Subject {
private List<Observer> observers = new ArrayList<>();
public void attach(Observer observer) { observers.add(observer); }
public void detach(Observer observer) { observers.remove(observer); }
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
class ConcreteObserver implements Observer {
public void update(String message) { System.out.println("Received: " + message); }
}
3. 命令模式 (Command Pattern)
将请求封装为一个对象,从而使你可以用不同的请求对客户进行参数化。
interface Command {
void execute();
}
class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) { this.receiver = receiver; }
public void execute() { receiver.action(); }
}
class Receiver {
public void action() { /* 执行实际动作 */ }
}
class Invoker {
private Command command;
public void setCommand(Command command) { this.command = command; }
public void executeCommand() { command.execute(); }
}
4. 状态模式 (State Pattern)
允许一个对象在其内部状态改变时改变其行为。
interface State {
void handle(Context context);
}
class ConcreteStateA implements State {
public void handle(Context context) {
context.setState(new ConcreteStateB());
System.out.println("Switch to State B");
}
}
class ConcreteStateB implements State {
public void handle(Context context) {
context.setState(new ConcreteStateA());
System.out.println("Switch to State A");
}
}
class Context {
private State state;
public Context(State state) { this.state = state; }
public void setState(State state) { this.state = state; }
public void request() { state.handle(this); }
}
5. 模板方法模式 (Template Method Pattern)
定义了一个算法的骨架,而将一些步骤延迟到子类中。
abstract class AbstractClass {
public final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
}
protected abstract void primitiveOperation1();
protected abstract void primitiveOperation2();
}
class ConcreteClass extends AbstractClass {
protected void primitiveOperation1() { /* 实现操作1 */ }
protected void primitiveOperation2() { /* 实现操作2 */ }
}
6. 中介者模式 (Mediator Pattern)
用一个中介对象来封装一系列的对象交互。
interface Mediator {
void notify(Object sender, String ev);
}
class ConcreteMediator implements Mediator {
private Component1 component1;
private Component2 component2;
public ConcreteMediator(Component1 c1, Component2 c2) {
this.component1 = c1;
this.component2 = c2;
}
public void notify(Object sender, String ev) {
if (ev.equals("A")) {
component2.doC();
} else if (ev.equals("D")) {
component1.doB();
}
}
}
class Component1 {
private Mediator mediator;
public Component1(Mediator mediator) { this.mediator = mediator; }
public void doA() { mediator.notify(this, "A"); }
public void doB() { System.out.println("Doing B"); }
}
class Component2 {
private Mediator mediator;
public Component2(Mediator mediator) { this.mediator = mediator; }
public void doC() { System.out.println("Doing C"); }
public void doD() { mediator.notify(this, "D"); }
}
7. 迭代器模式 (Iterator Pattern)
提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。
interface Iterator {
boolean hasNext();
Object next();
}
interface Container {
Iterator getIterator();
}
class NameRepository implements Container {
public String names[] = {"Robert", "John", "Julie", "Lora"};
public Iterator getIterator() {
return new NameIterator();
}
private class NameIterator implements Iterator {
int index;
public boolean hasNext() {
if (index < names.length) {
return true;
}
return false;
}
public Object next() {
if (this.hasNext()) {
return names[index++];
}
return null;
}
}
}
8. 访问者模式 (Visitor Pattern)
在不改变数据结构的前提下,增加作用于一组对象元素的新功能。
interface Element {
void accept(Visitor v);
}
interface Visitor {
void visitConcreteElementA(ConcreteElementA a);
void visitConcreteElementB(ConcreteElementB b);
}
class ConcreteElementA implements Element {
public void accept(Visitor v) { v.visitConcreteElementA(this); }
public void operationA() { /* 操作A */ }
}
class ConcreteElementB implements Element {
public void accept(Visitor v) { v.visitConcreteElementB(this); }
public void operationB() { /* 操作B */ }
}
class ConcreteVisitor1 implements Visitor {
public void visitConcreteElementA(ConcreteElementA a) { a.operationA(); }
public void visitConcreteElementB(ConcreteElementB b) { b.operationB(); }
}
class ConcreteVisitor2 implements Visitor {
public void visitConcreteElementA(ConcreteElementA a) { a.operationA(); }
public void visitConcreteElementB(ConcreteElementB b) { b.operationB(); }
}
以上只是每种设计模式的一个简单示例。在实际开发过程中,你需要根据具体的需求和场景选择合适的设计模式。设计模式不仅帮助解决常见问题,还促进了代码复用、增强了程序的可维护性和扩展性。理解并熟练运用这些模式,可以帮助开发者编写出更加优雅和高效的代码。