24种Java常用设计模式基本原理导读(Java常用24种设计模式原理详解入门)
原创
一、设计模式概述
设计模式(Design Pattern)是一套被反复使用、多数人知晓、经过分类编目、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人明白、保证代码可靠性。在Java编程中,有24种常用的设计模式,它们被分为三类:创建型、结构型和行为型。
二、创建型模式
创建型模式关键包括以下5种模式,关键用于创建对象,这些模式关注对象的创建过程,令对象的创建更加灵活。
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 {
}
public class ConcreteProductA implements Product {
}
public class ConcreteProductB implements Product {
}
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.add("PartA");
}
@Override
public void buildPartB() {
product.add("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 add(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 field;
public ConcretePrototypeA(String field) {
this.field = field;
}
@Override
public Prototype clone() {
return new ConcretePrototypeA(field);
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
}
三、结构型模式
结构型模式关键包括以下7种模式,关键用于处理类和对象之间的关系,这些模式关注类和对象的组合。
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() {
System.out.println("Specific request.");
}
}
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();
System.out.println("RefinedAbstractionA");
}
}
public abstract class Implementor {
public abstract void operationImpl();
}
public class ConcreteImplementorA extends Implementor {
@Override
public void operationImpl() {
System.out.println("ConcreteImplementorA");
}
}
3. 组合模式(Composite)
组合模式将对象组合成树形结构以描述“部分-整体”的层次结构,令客户可以统一使用单个对象和组合对象。
public abstract class Component {
public abstract void operation();
}
public class Leaf extends Component {
@Override
public void operation() {
System.out.println("Leaf");
}
}
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() {
System.out.println("ConcreteComponent");
}
}
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();
System.out.println("ConcreteDecoratorA");
}
}
5. 门面模式(Facade)
门面模式为一组繁复的子系统提供一个统一的接口,令子系统更容易使用。
public class Facade {
private SubsystemA subsystemA;
private SubsystemB subsystemB;
private SubsystemC subsystemC;
public Facade() {
subsystemA = new SubsystemA();
subsystemB = new SubsystemB();
subsystemC = new SubsystemC();
}
public void operation() {
subsystemA.operationA();
subsystemB.operationB();
subsystemC.operationC();
}
}
public class SubsystemA {
public void operationA() {
System.out.println("SubsystemA");
}
}
public class SubsystemB {
public void operationB() {
System.out.println("SubsystemB");
}
}
public class SubsystemC {
public void operationC() {
System.out.println("SubsystemC");
}
}
6. 享元模式(Flyweight)
享元模式运用共享技术有效地拥护大量细粒度的对象。
public interface Flyweight {
void operation(int extrinsicState);
}
public class ConcreteFlyweight implements Flyweight {
private String intrinsicState;
public ConcreteFlyweight(String intrinsicState) {
this.intrinsicState = intrinsicState;
}
@Override
public void operation(int extrinsicState) {
System.out.println("Intrinsic State: " + intrinsicState + ", Extrinsic State: " + extrinsicState);
}
}
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() {
System.out.println("RealSubject");
}
}
public class Proxy implements Subject {
private RealSubject realSubject;
public Proxy(RealSubject realSubject) {
this.realSubject = realSubject;
}
@Override
public void request() {
realSubject.request();
}
}
四、行为型模式
行为型模式关键包括以下11种模式,关键用于处理对象之间的通信关系,这些模式关注对象之间的交互。
1. 职责链模式(Chain of Responsibility)
职责链模式使多个对象都有机会处理请求,从而避免了请求发送者和接收者之间的耦合关系。
public abstract class Handler {
private Handler nextHandler;
public void setNextHandler(Handler nextHandler) {
this.nextHandler = nextHandler;
}
public final void handleRequest(int request) {
if (nextHandler != null) {
nextHandler.handleRequest(request);
} else {
handleIt(request);
}
}
protected abstract void handleIt(int request);
}
public class ConcreteHandlerA extends Handler {
@Override
protected void handleIt(int request) {
if (request < 10) {
System.out.println("ConcreteHandlerA handled request " + request);
} else {
System.out.println("ConcreteHandlerA doesn't handle request " + request);
}
}
}
public class ConcreteHandlerB extends Handler {
@Override
protected void handleIt(int request) {
if (request < 20) {
System.out.println("ConcreteHandlerB handled request " + request);
} else {
System.out.println("ConcreteHandlerB doesn't handle request " + request);
}
}
}
2. 命令模式(Command)
命令模式将请求封装为一个对象,从而可以使用不同的请求、队列或日志来参数化其他对象。
public interface Command {
void execute();
}
public class Light {
public void turnOn() {
System.out.println("Light is on");
}
public void turnOff() {
System.out.println("Light is off");
}
}
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
}
public class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOff();
}
}
public class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
3. 解释器模式(Interpreter)
解释器模式为语言创建解释器,用来解释该语言中的句子。
public interface Expression {
int interpret();
}
public class NumberExpression implements Expression {
private int number;
public NumberExpression(int number) {
this.number = number;
}
@Override
public int interpret() {
return number;
}
}
public class AddExpression implements Expression {
private Expression left;
private Expression right;
public AddExpression(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 AddExpression(new NumberExpression(7), new NumberExpression(8));
System.out.println(expression.interpret());
}
}
4. 迭代器模式(Iterator)
迭代器模式提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露其内部的描述。
public interface Iterator {
boolean hasNext();
Object next();
}
public interface Aggregate {
Iterator iterator();
void add(Object object);
void remove(Object object);
}
public class ConcreteAggregate implements Aggregate {
private List
@Override
public Iterator iterator() {
return new ConcreteIterator(list);
}
@Override
public void add(Object object) {
list.add(object);
}
@Override
public void remove(Object object) {
list.remove(object);
}
}
public class ConcreteIterator implements Iterator {
private List
private int index;
public ConcreteIterator(List
this.list = list;
this.index = 0;
}
@Override
public boolean hasNext() {
return index < list.size();
}
@Override
public Object next() {
return list.get(index++);
}
}
5. 中介者模式(Mediator)
中介者模式定义一个对象来封装一组对象之间的交互,令对象之间不需要显式地彼此引用,从而降低它们之间的耦合。
public interface Mediator {
void send(String message, Colleague colleague);
}
public interface Colleague {
void receive(String message);
}
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 class ConcreteColleague1 implements Colleague {
private Mediator mediator;
public ConcreteColleague1(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void receive(String message) {
System.out.println("ConcreteColleague1 received message: " + message);
}
public void send(String message) {
mediator.send(message, this);
}
}
public class ConcreteColleague2 implements Colleague {
private Mediator mediator;
public ConcreteColleague2(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void receive(String message) {
System.out.println("ConcreteColleague2 received message: " + message);
}
public void send(String message) {
mediator.send(message, this);
}
}
6. 备忘录模式(Memento)
备忘录模式捕获一个对象的内部状态,并在该对象之外保存这个状态,以便稍后恢复它。
public class Memento {
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = 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 interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
}
public class ConcreteSubject implements Subject {
private List
observers = new ArrayList<>(); private int state;
@Override
public void attach(Observer observer) {
observers.add(observer);
}
@Override
public void detach(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update();
}
}
public void setState(int state) {
this.state = state;
notifyObservers();
}
public int getState() {
return state;
}
}
public class ConcreteObserver implements Observer {
private ConcreteSubject subject;
private int state;
public ConcreteObserver(ConcreteSubject subject) {
this.subject = subject;
this.state = subject.getState();
}
@Override
public void update() {
this.state = subject