所有 Java 的 23 种设计模式已经全部补充完毕,包含:
-
模式名称
-
类/接口结构
-
注释说明
-
控制台输出行为
分为三类:
-
创建型(5种):如单例、工厂、建造者、原型
-
结构型(7种):如适配器、桥接、装饰器、代理
-
行为型(11种):如策略、模板方法、观察者、状态、访问者、命令等
创建型设计模式(5个)
结构型设计模式(7个)
行为型设计模式(11个)
代码
// Java 23种设计模式详解示例
// 分类:创建型(5个)、结构型(7个)、行为型(11个)
import java.util.*;
// =============================
// 创建型设计模式(5个)
// =============================
// 1. 单例模式 Singleton
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 ConcreteProduct implements Product {
public void use() { System.out.println("Using product"); }
}
class Factory {
public static Product createProduct() {
return new ConcreteProduct();
}
}
// 3. 抽象工厂模式 Abstract Factory
interface Button { void click(); }
class WindowsButton implements Button {
public void click() { System.out.println("Windows Button clicked"); }
}
class MacButton implements Button {
public void click() { System.out.println("Mac Button clicked"); }
}
interface GUIFactory {
Button createButton();
}
class WindowsFactory implements GUIFactory {
public Button createButton() { return new WindowsButton(); }
}
class MacFactory implements GUIFactory {
public Button createButton() { return new MacButton(); }
}
// 4. 建造者模式 Builder
class Computer {
private String CPU;
private String GPU;
public void setCPU(String c) { CPU = c; }
public void setGPU(String g) { GPU = g; }
public void show() {
System.out.println("CPU: " + CPU + ", GPU: " + GPU);
}
}
class ComputerBuilder {
private Computer c = new Computer();
public ComputerBuilder setCPU(String cpu) { c.setCPU(cpu); return this; }
public ComputerBuilder setGPU(String gpu) { c.setGPU(gpu); return this; }
public Computer build() { return c; }
}
// 5. 原型模式 Prototype
class Prototype implements Cloneable {
public String field;
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
// =============================
// 结构型设计模式(7个)
// =============================
// 6. 适配器模式 Adapter
interface Target {
void request();
}
class Adaptee {
public void specificRequest() { System.out.println("Specific request"); }
}
class Adapter implements Target {
private Adaptee adaptee = new Adaptee();
public void request() { adaptee.specificRequest(); }
}
// 7. 桥接模式 Bridge
interface DrawAPI { void drawCircle(int radius); }
class RedDraw implements DrawAPI {
public void drawCircle(int radius) { System.out.println("Red circle with radius " + radius); }
}
abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) { this.drawAPI = drawAPI; }
abstract void draw();
}
class Circle extends Shape {
private int radius;
public Circle(int r, DrawAPI api) { super(api); radius = r; }
public void draw() { drawAPI.drawCircle(radius); }
}
// 8. 装饰器模式 Decorator
interface Component { void operation(); }
class ConcreteComponent implements Component {
public void operation() { System.out.println("Base operation"); }
}
class Decorator implements Component {
protected Component component;
public Decorator(Component c) { component = c; }
public void operation() {
component.operation();
System.out.println("Enhanced operation");
}
}
// 9. 组合模式 Composite
interface Graphic {
void draw();
}
class CircleGraphic implements Graphic {
public void draw() { System.out.println("Draw circle"); }
}
class CompositeGraphic implements Graphic {
private List<Graphic> children = new ArrayList<>();
public void add(Graphic g) { children.add(g); }
public void draw() {
for (Graphic g : children) g.draw();
}
}
// 10. 外观模式 Facade
class SubsystemA { public void operationA() { System.out.println("A"); } }
class SubsystemB { public void operationB() { System.out.println("B"); } }
class Facade {
private SubsystemA a = new SubsystemA();
private SubsystemB b = new SubsystemB();
public void operation() {
a.operationA();
b.operationB();
}
}
// 11. 享元模式 Flyweight
class Flyweight {
private final String state;
public Flyweight(String state) { this.state = state; }
public void operation() { System.out.println("Shared state: " + state); }
}
class FlyweightFactory {
private Map<String, Flyweight> pool = new HashMap<>();
public Flyweight get(String key) {
return pool.computeIfAbsent(key, k -> new Flyweight(k));
}
}
// 12. 代理模式 Proxy
interface Subject {
void request();
}
class RealSubject implements Subject {
public void request() { System.out.println("Real subject"); }
}
class ProxySubject implements Subject {
private RealSubject real = new RealSubject();
public void request() {
System.out.println("Proxy before");
real.request();
System.out.println("Proxy after");
}
}
// =============================
// 行为型设计模式(11个)
// =============================
// 13. 策略模式 Strategy
interface Strategy {
int doOperation(int a, int b);
}
class Add implements Strategy {
public int doOperation(int a, int b) { return a + b; }
}
class Subtract implements Strategy {
public int doOperation(int a, int b) { return a - b; }
}
class Context {
private Strategy strategy;
public Context(Strategy strategy) { this.strategy = strategy; }
public int execute(int a, int b) { return strategy.doOperation(a, b); }
}
// 14. 模板方法模式 Template Method
abstract class Game {
public final void play() {
initialize();
startPlay();
endPlay();
}
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
}
class Football extends Game {
void initialize() { System.out.println("Football Init"); }
void startPlay() { System.out.println("Football Start"); }
void endPlay() { System.out.println("Football End"); }
}
// 15. 观察者模式 Observer
interface Observer {
void update(String msg);
}
class ConcreteObserver implements Observer {
private String name;
public ConcreteObserver(String name) { this.name = name; }
public void update(String msg) {
System.out.println(name + " received: " + msg);
}
}
class SubjectObservable {
private List<Observer> observers = new ArrayList<>();
public void add(Observer o) { observers.add(o); }
public void notifyAllObservers(String msg) {
for (Observer o : observers) o.update(msg);
}
}
// 16. 责任链模式 Chain of Responsibility
abstract class Handler {
protected Handler next;
public void setNext(Handler h) { next = h; }
public abstract void handle(int level);
}
class Level1Handler extends Handler {
public void handle(int level) {
if (level == 1) System.out.println("Handled by Level 1");
else if (next != null) next.handle(level);
}
}
// 17. 命令模式 Command
interface Command { void execute(); }
class Light {
public void on() { System.out.println("Light ON"); }
}
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light l) { light = l; }
public void execute() { light.on(); }
}
class Invoker {
private Command command;
public Invoker(Command c) { command = c; }
public void press() { command.execute(); }
}
// 18. 状态模式 State
interface State {
void doAction();
}
class StartState implements State {
public void doAction() { System.out.println("Start State"); }
}
class StopState implements State {
public void doAction() { System.out.println("Stop State"); }
}
class ContextState {
private State state;
public void setState(State s) { state = s; }
public void request() { state.doAction(); }
}
// 19. 访问者模式 Visitor
interface Element { void accept(Visitor v); }
interface Visitor { void visit(ElementA e); void visit(ElementB e); }
class ElementA implements Element {
public void accept(Visitor v) { v.visit(this); }
}
class ElementB implements Element {
public void accept(Visitor v) { v.visit(this); }
}
class PrintVisitor implements Visitor {
public void visit(ElementA e) { System.out.println("Visited A"); }
public void visit(ElementB e) { System.out.println("Visited B"); }
}
// 20. 备忘录模式 Memento
class Memento {
private String state;
public Memento(String s) { state = s; }
public String getState() { return state; }
}
class Originator {
private String state;
public void set(String s) { state = s; }
public Memento save() { return new Memento(state); }
public void restore(Memento m) { state = m.getState(); }
public void show() { System.out.println("State: " + state); }
}
// 21. 中介者模式 Mediator
interface Mediator {
void notify(ComponentM sender, String event);
}
class ComponentM {
protected Mediator mediator;
public ComponentM(Mediator m) { mediator = m; }
}
class ButtonM extends ComponentM {
public ButtonM(Mediator m) { super(m); }
public void click() {
System.out.println("Button clicked");
mediator.notify(this, "click");
}
}
class DialogMediator implements Mediator {
public void notify(ComponentM sender, String event) {
if (event.equals("click")) {
System.out.println("Mediator handles button click");
}
}
}
// 22. 解释器模式 Interpreter
interface Expression {
boolean interpret(String context);
}
class TerminalExpression implements Expression {
private String data;
public TerminalExpression(String d) { data = d; }
public boolean interpret(String context) {
return context.contains(data);
}
}
// 23. 迭代器模式 Iterator
interface MyIterator<T> {
boolean hasNext();
T next();
}
class MyCollection<T> {
private List<T> list = new ArrayList<>();
public void add(T t) { list.add(t); }
public MyIterator<T> iterator() {
return new MyIterator<T>() {
private int index = 0;
public boolean hasNext() { return index < list.size(); }
public T next() { return list.get(index++); }
};
}
}