在Java中,设计模式是一种解决特定问题的可重用方案。设计模式大致可以分为三类:创建型、结构型和行为型。本文将为您详细阐述23种设计模式,并给出部分代码示例。
1. 创建型模式
创建型模式主要关注对象的创建机制,解决如何创建对象的问题。
(1)单例模式(Singleton)
单例模式确保一个类只有一个实例,并提供全局访问点。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
(2)工厂方法模式(Factory Method)
工厂方法模式定义一个创建对象的接口,让子类决定实例化哪个类。
interface Product {
void use();
}
class ConcreteProductA implements Product {
public void use() {
System.out.println("Using Product A");
}
}
class ConcreteProductB implements Product {
public void use() {
System.out.println("Using Product B");
}
}
abstract class Creator {
public abstract Product factoryMethod();
}
class ConcreteCreatorA extends Creator {
public Product factoryMethod() {
return new ConcreteProductA();
}
}
class ConcreteCreatorB extends Creator {
public Product factoryMethod() {
return new ConcreteProductB();
}
}
(3)抽象工厂模式(Abstract Factory)
抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而无需指定其具体类。
interface AbstractProductA {}
interface AbstractProductB {}
class ConcreteProductA1 implements AbstractProductA {}
class ConcreteProductB1 implements AbstractProductB {}
class ConcreteProductA2 implements AbstractProductA {}
class ConcreteProductB2 implements AbstractProductB {}
interface AbstractFactory {
AbstractProductA createProductA();
AbstractProductB createProductB();
}
class ConcreteFactory1 implements AbstractFactory {
public AbstractProductA createProductA() {
return new ConcreteProductA1();
}
public AbstractProductB createProductB() {
return new ConcreteProductB1();
}
}
class ConcreteFactory2 implements AbstractFactory {
public AbstractProductA createProductA() {
return new ConcreteProductA2();
}
public AbstractProductB createProductB() {
return new ConcreteProductB2();
}
}
(4)建造者模式(Builder)
建造者模式将一个复杂对象的构建与其表示分离,使同样的构建过程可以创建不同的表示。
class Product {
private String partA;
private String partB;
public void setPartA(String partA) { this.partA = partA; }
public void setPartB(String partB) { this.partB = partB; }
}
abstract class Builder {
protected Product product = new Product();
public abstract void buildPartA();
public abstract void buildPartB();
public Product getResult() { return product; }
}
class ConcreteBuilder extends Builder {
public void buildPartA() { product.setPartA("Part A"); }
public void buildPartB() { product.setPartB("Part B"); }
}
class Director {
private Builder builder;
public Director(Builder builder) { this.builder = builder; }
public void construct() {
builder.buildPartA();
builder.buildPartB();
}
}
(5)原型模式(Prototype)
原型模式通过复制现有的对象来创建新对象,而不是通过构造函数。
abstract class Prototype {
public abstract Prototype clone();
}
class ConcretePrototype extends Prototype {
public Prototype clone() {
return new ConcretePrototype();
}
}
2. 结构型模式
结构型模式主要关注类和对象的组合,用于形成更大的结构。
(1)适配器模式(Adapter)
适配器模式将一个类的接口转换成客户端希望的另一个接口。
class Target {
public void request() {
System.out.println("Target request");
}
}
class Adaptee {
public void specificRequest() {
System.out.println("Adaptee specific request");
}
}
class Adapter extends Target {
private Adaptee adaptee = new Adaptee();
@Override
public void request() {
adaptee.specificRequest();
}
}
(2)装饰者模式(Decorator)
装饰者模式动态地给对象添加一些额外的职责。
interface Component {
void operation();
}
class ConcreteComponent implements Component {
public void operation() {
System.out.println("ConcreteComponent operation");
}
}
class Decorator implements Component {
private Component decoratedComponent;
public Decorator(Component component) {
this.decoratedComponent = component;
}
public void operation() {
decoratedComponent.operation();
System.out.println("Decorator operation");
}
}
(3)外观模式(Facade)
外观模式为子系统中的一组接口提供一个统一的高层接口,使子系统更易使用。
class SubSystemA {
public void operationA() { System.out.println("Operation A"); }
}
class SubSystemB {
public void operationB() { System.out.println("Operation B"); }
}
class Facade {
private SubSystemA a = new SubSystemA();
private SubSystemB b = new SubSystemB();
public void operation() {
a.operationA();
b.operationB();
}
}
(4)享元模式(Flyweight)
享元模式通过共享对象来减少内存占用。
import java.util.HashMap;
class Flyweight {
private String intrinsicState;
public Flyweight(String intrinsicState) {
this.intrinsicState = intrinsicState;
}
public void operation(String extrinsicState) {
System.out.println("Intrinsic: " + intrinsicState + ", Extrinsic: " + extrinsicState);
}
}
class FlyweightFactory {
private HashMap<String, Flyweight> flyweights = new HashMap<>();
public Flyweight getFlyweight(String key) {
if (!flyweights.containsKey(key)) {
flyweights.put(key, new Flyweight(key));
}
return flyweights.get(key);
}
}
(5)代理模式(Proxy)
代理模式为其他对象提供一个代理以控制对这个对象的访问。
interface Subject {
void request();
}
class RealSubject implements Subject {
public void request() {
System.out.println("RealSubject request");
}
}
class Proxy implements Subject {
private RealSubject realSubject;
public void request() {
if (realSubject == null) {
realSubject = new RealSubject();
}
realSubject.request();
}
}
3. 行为型模式
行为型模式主要关注对象之间的通信和职责分配。
(1)观察者模式(Observer)
观察者模式定义了一种一对多的依赖关系,以便当一个对象状态发生变化时,所有依赖于它的对象都会收到通知并自动更新。
import java.util.ArrayList;
import java.util.List;
interface Observer {
void update(String message);
}
class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) {
this.name = name;
}
public void update(String message) {
System.out.println(name + " received: " + message);
}
}
class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
(2)策略模式(Strategy)
策略模式定义了一系列算法,将每一个算法封装起来并使它们可以互相替换。
interface Strategy {
void execute();
}
class ConcreteStrategyA implements Strategy {
public void execute() {
System.out.println("Executing Strategy A");
}
}
class ConcreteStrategyB implements Strategy {
public void execute() {
System.out.println("Executing Strategy B");
}
}
class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.execute();
}
}
(3)命令模式(Command)
命令模式将请求封装成一个对象,从而允许用户使用不同的请求、队列或者记录日志。
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 Invoker(Command command) {
this.command = command;
}
public void invoke() {
command.execute();
}
}
(4)状态模式(State)
状态模式允许对象在内部状态改变时改变它的行为。
interface State {
void handle();
}
class ConcreteStateA implements State {
public void handle() {
System.out.println("Handling State A");
}
}
class Context {
private State state;
public void setState(State state) {
this.state = state;
}
public void request() {
state.handle();
}
}
(5)访问者模式(Visitor)
访问者模式允许您在不改变现有类的情况下添加新的操作。
interface Visitor {
void visit(ConcreteElementA elementA);
void visit(ConcreteElementB elementB);
}
interface Element {
void accept(Visitor visitor);
}
class ConcreteElementA implements Element {
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class ConcreteElementB implements Element {
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class ConcreteVisitor implements Visitor {
public void visit(ConcreteElementA elementA) {
System.out.println("Visiting Element A");
}
public void visit(ConcreteElementB elementB) {
System.out.println("Visiting Element B");
}
}
结论
以上详细介绍了23种设计模式中一些常用的模式及其实现示例。设计模式帮助我们解决软件设计中的常见问题,提高了代码的可复用性、可维护性和扩展性。理解和掌握这些设计模式,将对提升您的编程技能大有裨益。