设计模式是软件工程中的一种典型解决方案,它不是可以直接使用的代码,而是解决特定问题的一种最佳实践。Java作为一种面向对象的编程语言,广泛应用于企业级开发,因此设计模式在Java开发中占有重要的地位。下面,我们将对23种设计模式进行整体概述,并提供一些代码示例。
一、创建型模式
创建型模式主要关注对象的创建方式,常见的有:
-
单例模式(Singleton Pattern) 确保一个类只有一个实例并提供全局访问。 ```java public class Singleton { private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } ```
-
工厂方法模式(Factory Method Pattern) 定义一个创建对象的接口,由子类决定实例化哪一个类。 ```java interface Product { void use(); }
class ConcreteProductA implements Product { public void use() { System.out.println("Using product A"); } }
class Factory { public Product createProduct(String type) { if ("A".equals(type)) { return new ConcreteProductA(); } return null; // 可以扩展 } } ```
- 抽象工厂模式(Abstract Factory Pattern) 创建一组相关或相互依赖的对象,而无需指定具体类。 ```java interface AbstractFactory { Product createProductA(); Product createProductB(); }
class ConcreteFactory1 implements AbstractFactory { public Product createProductA() { return new ConcreteProductA(); } public Product createProductB() { return new ConcreteProductB(); } } ```
-
建造者模式(Builder Pattern) 将一个复杂对象的构建与其表示分离,使同样的构建过程可以创建不同的表示。 ```java class Product { private String partA; private String partB;
public void setPartA(String partA) { this.partA = partA; }
public void setPartB(String partB) { this.partB = partB; } }
class Builder { private Product product = new Product();
public void buildPartA() {
product.setPartA("Part A");
}
public void buildPartB() {
product.setPartB("Part B");
}
public Product getProduct() {
return product;
}
} ```
- 原型模式(Prototype Pattern)
通过复制现有实例来创建新实例。
java class Prototype implements Cloneable { public Object clone() throws CloneNotSupportedException { return super.clone(); } }
二、结构型模式
结构型模式通常涉及类和对象组合。常见的有:
- 适配器模式(Adapter Pattern) 将一个类的接口转换成客户端所希望的另一种接口。 ```java class Adaptee { public void specificRequest() { System.out.println("Special request"); } }
class Adapter extends Adaptee { public void request() { specificRequest(); } } ```
- 桥接模式(Bridge Pattern) 将抽象部分与实现部分分离,使它们可以独立变化。 ```java interface Implementor { void operation(); }
class ConcreteImplementorA implements Implementor { public void operation() { System.out.println("ConcreteImplementorA operation"); } }
abstract class Abstraction { protected Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation();
} ```
- 组合模式(Composite Pattern) 将对象组合成树形结构以表示“部分-整体”的层次结构。 ```java interface Component { void operation(); }
class Leaf implements Component { public void operation() { System.out.println("Leaf operation"); } }
class Composite implements Component {
private List
public void add(Component component) {
children.add(component);
}
public void operation() {
for (Component child : children) {
child.operation();
}
}
} ```
- 装饰者模式(Decorator Pattern) 动态地给一个对象增加一些额外的职责。 ```java interface Coffee { double cost(); }
class SimpleCoffee implements Coffee { public double cost() { return 5; } }
abstract class CoffeeDecorator implements Coffee { protected Coffee coffee;
public CoffeeDecorator(Coffee coffee) {
this.coffee = coffee;
}
}
class MilkDecorator extends CoffeeDecorator { public MilkDecorator(Coffee coffee) { super(coffee); }
public double cost() {
return coffee.cost() + 2;
}
} ```
-
外观模式(Facade Pattern) 为子系统中的一组接口提供一个一致的界面。 ```java class SubsystemA { public void operationA() { System.out.println("Operation A"); } }
class SubsystemB { public void operationB() { System.out.println("Operation B"); } }
class Facade { private SubsystemA subsystemA = new SubsystemA(); private SubsystemB subsystemB = new SubsystemB();
public void operation() { subsystemA.operationA(); subsystemB.operationB(); }
} ```
-
享元模式(Flyweight Pattern) 运用共享技术有效支持大量细粒度的对象。 ```java class Flyweight { private String intrinsicState;
public Flyweight(String intrinsicState) { this.intrinsicState = intrinsicState; } public void operation(String extrinsicState) { System.out.println("Intrinsic: " + intrinsicState + ", Extrinsic: " + extrinsicState); }
} ```
-
代理模式(Proxy Pattern) 为其他对象提供一个代理以控制对这个对象的访问。 ```java interface Subject { void request(); }
class RealSubject implements Subject { public void request() { System.out.println("RealSubject request"); } }
class Proxy implements Subject { private RealSubject realSubject = new RealSubject();
public void request() { System.out.println("Proxy request"); realSubject.request(); }
} ```
三、行为型模式
行为型模式主要关注对象之间的通信。常见的有:
-
模板方法模式(Template Method Pattern) 在一个方法中定义一个算法的框架,而将一些步骤延迟到子类中。 ```java abstract class AbstractClass { public final void templateMethod() { step1(); step2(); }
protected abstract void step1(); protected abstract void step2();
}
class ConcreteClass extends AbstractClass { protected void step1() { System.out.println("Step 1 implemented"); }
protected void step2() { System.out.println("Step 2 implemented"); }
} ```
-
策略模式(Strategy Pattern) 定义一系列算法,把它们一个个封装起来,并且使它们可以互换。 ```java interface Strategy { int doOperation(int num1, int num2); }
class Addition 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); }
} ```
-
观察者模式(Observer Pattern) 定义一种一对多的依赖关系,以便当一个对象改变状态时,它的所有依赖者都会受到通知。 ```java class Subject { private List
observers = new ArrayList<>(); public void attach(Observer observer) { observers.add(observer); } public void notifyObservers() { for (Observer observer : observers) { observer.update(); } }
}
interface Observer { void update(); } ```
-
中介者模式(Mediator Pattern) 用一个中介对象来封装一系列的对象交互。 ```java class Mediator { private Colleague colleague1; private Colleague colleague2;
public void setColleague1(Colleague colleague) { this.colleague1 = colleague; } public void setColleague2(Colleague colleague) { this.colleague2 = colleague; } public void mediate() { // Interaction logic }
}
class Colleague { private Mediator mediator;
public Colleague(Mediator mediator) { this.mediator = mediator; } // Other methods
} ```
-
命令模式(Command Pattern) 将一个请求封装为一个对象,从而可以用不同的请求对客户进行参数化。 ```java 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() { System.out.println("Receiver action"); } }
class Invoker { private Command command;
public void setCommand(Command command) { this.command = command; } public void executeCommand() { command.execute(); }
} ```
-
状态模式(State Pattern) 允许一个对象在其内部状态改变时改变它的行为。 ```java interface State { void handle(); }
class ConcreteStateA implements State { public void handle() { System.out.println("State A"); } }
class Context { private State state;
public void setState(State state) { this.state = state; } public void request() { state.handle(); }
} ```
-
备忘录模式(Memento Pattern) 在不违反封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。 ```java class Memento { private String state;
public Memento(String state) { this.state = state; } public String getState() { return state; }
}
class Originator { private String state;
public void setState(String state) { this.state = state; } public Memento saveStateToMemento() { return new Memento(state); } public void getStateFromMemento(Memento memento) { state = memento.getState(); }
} ```
-
迭代器模式(Iterator Pattern) 提供一种方法顺序访问一个聚合对象中的元素,而不暴露其内部表示。 ```java interface Iterator { boolean hasNext(); Object next(); }
interface Collection { Iterator createIterator(); }
class ConcreteCollection implements Collection { private List
public void add(Object item) { items.add(item); } public Iterator createIterator() { return new ConcreteIterator(this); } public List<Object> getItems() { return items; }
}
class ConcreteIterator implements Iterator { private ConcreteCollection collection; private int index = 0;
public ConcreteIterator(ConcreteCollection collection) { this.collection = collection; } public boolean hasNext() { return index < collection.getItems().size(); } public Object next() { return collection.getItems().get(index++); }
} ```
-
访问者模式(Visitor Pattern) 表示一个作用于某对象结构中的各元素的操作。 ```java interface Visitor { void visit(ElementA element); void visit(ElementB element); }
interface Element { void accept(Visitor visitor); }
class ElementA implements Element { public void accept(Visitor visitor) { visitor.visit(this); } }
class ElementB implements Element { public void accept(Visitor visitor) { visitor.visit(this); } }
class ConcreteVisitor implements Visitor { public void visit(ElementA element) { System.out.println("Visiting Element A"); }
public void visit(ElementB element) { System.out.println("Visiting Element B"); }
} ```
-
组合模式(Chain of Responsibility Pattern) 使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。 ```java abstract class Handler { protected Handler next;
public void setNext(Handler next) { this.next = next; } public abstract void handleRequest(int request);
}
class ConcreteHandlerA extends Handler { public void handleRequest(int request) { if (request < 10) { System.out.println("Handler A handling request " + request); } else if (next != null) { next.handleRequest(request); } } }
class ConcreteHandlerB extends Handler { public void handleRequest(int request) { if (request >= 10 && request < 20) { System.out.println("Handler B handling request " + request); } else if (next != null) { next.handleRequest(request); } } } ```
-
** mediator模式(Mediator Pattern)** 定义一个中介对象来封装一系列对象间的交互。
```java class Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2;
public void setColleague1(ConcreteColleague1 colleague) { this.colleague1 = colleague; } public void setColleague2(ConcreteColleague2 colleague) { this.colleague2 = colleague; } public void colleague1Changed() { // Handle changes from colleague1 } public void colleague2Changed() { // Handle changes from colleague2 }
}
class ConcreteColleague1 { private Mediator mediator;
public ConcreteColleague1(Mediator mediator) { this.mediator = mediator; } public void change() { mediator.colleague1Changed(); }
}
class ConcreteColleague2 { private Mediator mediator;
public ConcreteColleague2(Mediator mediator) { this.mediator = mediator; } public void change() { mediator.colleague2Changed(); }
} ```
每种设计模式都有其适用的场景和优势,开发者可以根据具体需求选择合适的设计模式来优化代码结构,提高系统的可维护性和扩展性。因此,深入理解设计模式是进行高效Java开发的关键。希望抛砖引玉,能够帮助你更好地掌握Java设计模式及其应用。