漫谈设计模式-技术要点详解(设计模式深度解析:核心技术要点全览)

原创
ithorizon 6个月前 (10-21) 阅读数 26 #后端开发

漫谈设计模式-技术要点详解

一、设计模式概述

设计模式是软件工程中的一种常见技术,它提供了一套经过验证的解决方案,用于解决软件开发中常见的问题。设计模式可以帮助我们减成本时间代码的可复用性、可维护性和可扩展性。本文将深入解析设计模式的核心技术要点,帮助读者更好地懂得和应用设计模式。

二、设计模式的分类

设计模式关键分为三大类:创建型、结构型和行为型。下面将分别介绍这三种类型的设计模式。

创建型设计模式

创建型设计模式关键关注对象的创建过程,关键有以下五种模式:

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)

工厂方法模式定义一个接口用于创建对象,但让子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类。

public interface Product {

void operation();

}

public class ConcreteProductA implements Product {

@Override

public void operation() {

// 实现具体操作

}

}

public class ConcreteProductB implements Product {

@Override

public void operation() {

// 实现具体操作

}

}

public abstract class Creator {

public abstract Product factoryMethod();

}

public class ConcreteCreatorA extends Creator {

@Override

public Product factoryMethod() {

return new ConcreteProductA();

}

}

public class ConcreteCreatorB extends Creator {

@Override

public Product factoryMethod() {

return new ConcreteProductB();

}

}

3. 抽象工厂模式(Abstract Factory)

抽象工厂模式提供了一个接口,用于创建相关或依赖性对象的家族,而不需要明确指定具体类。

public interface AbstractFactory {

ProductA createProductA();

ProductB createProductB();

}

public class ConcreteFactoryA implements AbstractFactory {

@Override

public ProductA createProductA() {

return new ConcreteProductA();

}

@Override

public ProductB createProductB() {

return new ConcreteProductB();

}

}

public class ConcreteFactoryB implements AbstractFactory {

@Override

public ProductA createProductA() {

return new ConcreteProductC();

}

@Override

public ProductB createProductB() {

return new ConcreteProductD();

}

}

4. 建造者模式(Builder)

建造者模式将一个复杂化对象的构建与其即分离,让同样的构建过程可以创建不同的即。

public abstract class Builder {

public abstract void buildPartA();

public abstract void buildPartB();

public abstract Product getResult();

}

public class ConcreteBuilderA extends Builder {

private Product product = new Product();

@Override

public void buildPartA() {

product.addPart("PartA");

}

@Override

public void buildPartB() {

product.addPart("PartB");

}

@Override

public Product getResult() {

return product;

}

}

public class Director {

private Builder builder;

public Director(Builder builder) {

this.builder = builder;

}

public void construct() {

builder.buildPartA();

builder.buildPartB();

}

}

public class Product {

private List parts = new ArrayList<>();

public void addPart(String part) {

parts.add(part);

}

public String show() {

return String.join(", ", parts);

}

}

5. 原型模式(Prototype)

原型模式通过复制现有的实例来创建新的实例,而不是通过构造函数创建。

public abstract class Prototype {

public abstract Prototype clone();

}

public class ConcretePrototypeA extends Prototype {

private String data;

public ConcretePrototypeA(String data) {

this.data = data;

}

@Override

public Prototype clone() {

return new ConcretePrototypeA(data);

}

}

结构型设计模式

结构型设计模式关注类和对象之间的组合,关键有以下七种模式:

1. 适配器模式(Adapter)

适配器模式允许将一个类的接口转换成客户期望的另一个接口,让原本接口不兼容的类可以一起工作。

public interface Target {

void request();

}

public class Adapter implements Target {

private Adaptee adaptee;

public Adapter(Adaptee adaptee) {

this.adaptee = adaptee;

}

@Override

public void request() {

adaptee.specificRequest();

}

}

public class Adaptee {

public void specificRequest() {

// ...

}

}

2. 桥接模式(Bridge)

桥接模式将抽象部分与实现部分分离,使它们可以自立变化。

public abstract class Abstraction {

protected Implementor implementor;

public Abstraction(Implementor implementor) {

this.implementor = implementor;

}

public abstract void operation();

}

public class RefinedAbstractionA extends Abstraction {

public RefinedAbstractionA(Implementor implementor) {

super(implementor);

}

@Override

public void operation() {

implementor.operationImpl();

}

}

public abstract class Implementor {

public abstract void operationImpl();

}

public class ConcreteImplementorA extends Implementor {

@Override

public void operationImpl() {

// ...

}

}

3. 组合模式(Composite)

组合模式允许将对象组合成树形结构,以即部分-整体的层次结构。

public abstract class Component {

public abstract void operation();

}

public class Leaf extends Component {

@Override

public void operation() {

// ...

}

}

public class Composite extends Component {

private List children = new ArrayList<>();

@Override

public void operation() {

for (Component child : children) {

child.operation();

}

}

public void add(Component component) {

children.add(component);

}

public void remove(Component component) {

children.remove(component);

}

}

4. 装饰器模式(Decorator)

装饰器模式动态地给一个对象添加一些额外的职责,而不改变其接口。

public abstract class Component {

public abstract void operation();

}

public class ConcreteComponent extends Component {

@Override

public void operation() {

// ...

}

}

public abstract class Decorator extends Component {

private Component component;

public Decorator(Component component) {

this.component = component;

}

@Override

public void operation() {

component.operation();

}

}

public class ConcreteDecoratorA extends Decorator {

public ConcreteDecoratorA(Component component) {

super(component);

);

}

@Override

public void operation() {

super.operation();

// 添加额外的职责

}

}

5. 门面模式(Facade)

门面模式提供了一个统一的接口,用于访问子系统中的一群接口。

public class Facade {

private SubsystemA subsystemA;

private SubsystemB subsystemB;

public Facade() {

subsystemA = new SubsystemA();

subsystemB = new SubsystemB();

}

public void operation() {

subsystemA.operationA();

subsystemB.operationB();

}

}

public class SubsystemA {

public void operationA() {

// ...

}

}

public class SubsystemB {

public void operationB() {

// ...

}

}

6. 享元模式(Flyweight)

享元模式运用共享技术有效地拥护大量细粒度的对象。

public interface Flyweight {

void operation();

}

public class ConcreteFlyweight implements Flyweight {

private String intrinsicState;

public ConcreteFlyweight(String intrinsicState) {

this.intrinsicState = intrinsicState;

}

@Override

public void operation() {

// ...

}

}

public class UnsharedConcreteFlyweight implements Flyweight {

@Override

public void operation() {

// ...

}

}

public class FlyweightFactory {

private Map flyweights = new HashMap<>();

public Flyweight getFlyweight(String key) {

if (!flyweights.containsKey(key)) {

flyweights.put(key, new ConcreteFlyweight(key));

}

return flyweights.get(key);

}

}

7. 代理模式(Proxy)

代理模式为其他对象提供一个代理以控制对这个对象的访问。

public interface Subject {

void request();

}

public class RealSubject implements Subject {

@Override

public void request() {

// ...

}

}

public class Proxy implements Subject {

private RealSubject realSubject;

public Proxy(RealSubject realSubject) {

this.realSubject = realSubject;

}

@Override

public void request() {

realSubject.request();

}

}

行为型设计模式

行为型设计模式关注对象之间的通信,关键有以下十一种模式:

1. 职责链模式(Chain of Responsibility)

职责链模式使多个对象都有机会处理请求,从而避免了请求发送者和接收者之间的耦合关系。

public abstract class Handler {

private Handler nextHandler;

public void setNextHandler(Handler nextHandler) {

this.nextHandler = nextHandler;

}

public final void handleRequest(Request request) {

if (nextHandler != null) {

nextHandler.handleRequest(request);

} else {

handle(request);

}

}

protected abstract void handle(Request request);

}

public class ConcreteHandlerA extends Handler {

@Override

protected void handle(Request request) {

// ...

}

}

public class ConcreteHandlerB extends Handler {

@Override

protected void handle(Request request) {

// ...

}

}

public class Request {

// ...

}

2. 命令模式(Command)

命令模式将请求封装为一个对象,从而可以使用不同的请求、队列或日志来参数化其他对象。

public interface Command {

void execute();

}

public class ConcreteCommandA implements Command {

private Receiver receiver;

public ConcreteCommandA(Receiver receiver) {

this.receiver = receiver;

}

@Override

public void execute() {

receiver.action();

}

}

public class Receiver {

public void action() {

// ...

}

}

public class Invoker {

private Command command;

public void setCommand(Command command) {

this.command = command;

}

public void executeCommand() {

command.execute();

}

}

3. 解释器模式(Interpreter)

解释器模式为语言创建解释器,用来解释该语言中的句子。

public interface Expression {

int interpret();

}

public class ConstantExpression implements Expression {

private int value;

public ConstantExpression(int value) {

this.value = value;

}

@Override

public int interpret() {

return value;

}

}

public class AdditionExpression implements Expression {

private Expression left;

private Expression right;

public AdditionExpression(Expression left, Expression right) {

this.left = left;

this.right = right;

}

@Override

public int interpret() {

return left.interpret() + right.interpret();

}

}

public class Interpreter {

public static void main(String[] args) {

Expression expression = new AdditionExpression(

new ConstantExpression(2),

new ConstantExpression(3)

);

System.out.println(expression.interpret());

}

}

4. 迭代器模式(Iterator)

迭代器模式提供了一种方法来访问聚合对象中各个元素,而又不暴露该对象的内部即。

public interface Iterator {

boolean hasNext();

Object next();

}

public interface Aggregate {

Iterator iterator();

}

public class ConcreteAggregate implements Aggregate {

private List items = new ArrayList<>();

public void add(Object item) {

items.add(item);

}

@Override

public Iterator iterator() {

return new ConcreteIterator(items);

}

}

public class ConcreteIterator implements Iterator {

private List items;

private int index = 0;

public ConcreteIterator(List items) {

this.items = items;

}

@Override

public boolean hasNext() {

return index < items.size();

}

@Override

public Object next() {

return items.get(index++);

}

}

5. 中介者模式(Mediator)

中介者模式定义一个对象来封装一组对象之间的交互。

public interface Mediator {

void send(String message, Colleague colleague);

}

public class ConcreteMediator implements Mediator {

private Colleague colleague1;

private Colleague colleague2;

public void setColleague1(Colleague colleague1) {

this.colleague1 = colleague1;

}

public void setColleague2(Colleague colleague2) {

this.colleague2 = colleague2;

}

@Override

public void send(String message, Colleague colleague) {

if (colleague == colleague1) {

colleague2.receive(message);

} else {

colleague1.receive(message);

}

}

}

public abstract class Colleague {

protected Mediator mediator;

public Colleague(Mediator mediator) {

this.mediator = mediator;

}

public abstract void send(String message);

public abstract void receive(String message);

}

public class ConcreteColleague1 extends Colleague {

public ConcreteColleague1(Mediator mediator) {

super(mediator);

}

@Override

public void send(String message) {

mediator.send(message, this);

}

@Override

public void receive(String message) {

// ...

}

}

public class ConcreteColleague2 extends Colleague {

public ConcreteColleague2(Mediator mediator) {

super(mediator);

}

@Override

public void send(String message) {

mediator.send(message, this);

}

@Override

public void receive(String message) {

// ...

}

}

6. 备忘录模式(Memento)

备忘录模式捕获一个对象的内部状态,并在该对象之外保存这个状态,以便稍后恢复它。

public class Memento {

private String state;

public Memento(String state) {

this.state = state;

}

public String getState() {

return state;

}

}

public class Originator {

private String state;

public void setState(String state) {

this.state = state;

}

public String getState() {

return state;

}

public Memento saveStateToMemento() {

return new Memento(state);

}

public void restoreStateFromMemento(Memento memento) {

state = memento.getState();

}

}

public class Caretaker {

private List mementoList = new ArrayList<>();

public void add(Memento state) {

mementoList.add(state);

}

public Memento get(int index) {

return mementoList.get(index);

}

}

7. 观察者模式(Observer)

观察者模式定义了一种一对多的依赖性关系,当一个对象改变状态时,所有依赖性于它的对象都会得到通知并自动更新。

public interface Observer {

void update();

}

public class ConcreteObserverA implements Observer {

private Subject subject;

public ConcreteObserverA(Subject subject) {

this.subject = subject;

this.subject.addObserver(this);

}

@Override

public void update() {

// ...

}

}

public interface Subject {

void addObserver(Observer observer);

void removeObserver(Observer observer);

void notifyObservers();

}

public class ConcreteSubject implements Subject {

private List observers = new ArrayList<>();

@Override

public void addObserver(Observer observer) {

observers.add(observer);

}

@Override

public void removeObserver(Observer observer) {

observers.remove(observer);

}

@Override

public void notifyObservers() {

for (Observer observer : observers) {

observer.update();

}

}

}

8. 状态模式(State)

状态模式允许一个对象在其内部状态改变时改变它的行为。

public abstract class State {

public abstract void handle(Request request);

}

public class ConcreteStateA extends State {

@Override

public void handle(Request request) {

// ...

}

}

public class ConcreteStateB extends State {

@Override

public void handle(Request request) {

// ...

}

}

public class Context {

private State state;

public void setState(State state) {

this.state = state;

}

public State getState() {

return state;

}

public void request(Request request) {

state.handle(request);

}

}

9. 策略模式(Strategy)

策略模式定义一系列算法,将每一个算法封装起来,并使它们可以互相替换。

public interface Strategy {

void algorithmInterface();

}

public class ConcreteStrategyA implements Strategy {

@Override

public void algorithmInterface() {

// ...

}

}

public class ConcreteStrategyB implements Strategy {

@Override

public void algorithmInterface() {

// ...

}

}

public class Context {

private Strategy strategy;

public Context(Strategy strategy) {

this.strategy = strategy;

}

public void setStrategy(Strategy strategy) {

this.strategy = strategy;

}

public void executeStrategy() {

strategy.algorithmInterface();

}

}

10. 模板方法模式(Template Method)

模板方法模式定义一个操作中的算法的骨架,而将一些步骤延迟

本文由IT视界版权所有,禁止未经同意的情况下转发

文章标签: 后端开发