Java实现所有设计模式

单例模式

饿汉式

public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return instance;
    }
}

懒汉式

public class Singleton {
    private static Singleton instance;
    private Singleton() {}
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

工厂模式

简单工厂

public class SimpleFactory {
    public static Product createProduct(String type) {
        if (type.equals("A")) {
            return new ConcreteProductA();
        } else if (type.equals("B")) {
            return new ConcreteProductB();
        }
        return null;
    }
}

工厂方法

public interface Factory {
    Product createProduct();
}
public class ConcreteFactoryA implements Factory {
    @Override
    public Product createProduct() {
        return new ConcreteProductA();
    }
}
public class ConcreteFactoryB implements Factory {
    @Override
    public Product createProduct() {
        return new ConcreteProductB();
    }
}

抽象工厂

public interface AbstractFactory {
    ProductA createProductA();
    ProductB createProductB();
}
public class ConcreteFactory1 implements AbstractFactory {
    @Override
    public ProductA createProductA() {
        return new ConcreteProductA1();
    }
    @Override
    public ProductB createProductB() {
        return new ConcreteProductB1();
    }
}
public class ConcreteFactory2 implements AbstractFactory {
    @Override
    public ProductA createProductA() {
        return new ConcreteProductA2();
    }
    @Override
    public ProductB createProductB() {
        return new ConcreteProductB2();
    }
}

策略模式

public interface Strategy {
    void algorithmInterface();
}
public class ConcreteStrategyA implements Strategy {
    @Override
    public void algorithmInterface() {
        // 算法A
    }
}
public class ConcreteStrategyB implements Strategy {
    @Override
    public void algorithmInterface() {
        // 算法B
    }
}
public class Context {
    private Strategy strategy;
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }
    public void contextInterface() {
        strategy.algorithmInterface();
    }
}

模板模式

public abstract class AbstractClass {
    public void templateMethod() {
        specificMethod();
        abstractMethod1();
        abstractMethod2();
    }
    public void specificMethod() {
        // 具体方法
    }
    public abstract void abstractMethod1();
    public abstract void abstractMethod2();
}
public class ConcreteClass extends AbstractClass {
    @Override
    public void abstractMethod1() {
        // 具体实现
    }
    @Override
    public void abstractMethod2() {
        // 具体实现
    }
}
public class ConcreteClass2 extends AbstractClass {
    @Override
    public void abstractMethod1() {
        // 具体实现
    }
    @Override
    public void abstractMethod2() {
        // 具体实现
    }
}

建造者模式

public class Product {
    private String partA;
    private String partB;
    private String partC;
    public void setPartA(String partA) {
        this.partA = partA;
    }
    public void setPartB(String partB) {
        this.partB = partB;
    }
    public void setPartC(String partC) {
        this.partC = partC;
    }
    public void show() {
        // 显示产品的特性
    }
}
public abstract class Builder {
    // 创建产品对象
    protected Product product = new Product();
    public abstract void buildPartA();
    public abstract void buildPartB();
    public abstract void buildPartC();
    // 返回产品对象
    public Product getResult() {
        return product;
    }
}
public class ConcreteBuilder extends Builder {
    @Override
    public void buildPartA() {
        product.setPartA("建造 PartA");
    }
    @Override
    public void buildPartB() {
        product.setPartA("建造 PartB");
    }
    @Override
    public void buildPartC() {
        product.setPartA("建造 PartC");
    }
}
public class Director {
    private Builder builder;
    public Director(Builder builder) {
        this.builder = builder;
    }
    public void setBuilder(Builder builder) {
        this.builder = builder;
    }
    public Product construct() {
        builder.buildPartA();
        builder.buildPartB();
        builder.buildPartC();
        return builder.getResult();
    }
}

原型模式

public class Prototype implements Cloneable {
    public Object clone() throws CloneNotSupportedException {
        Prototype proto = (Prototype) super.clone();
        return proto;
    }
}

适配器模式

public interface Target {
    void request();
}
public class Adaptee {
    public void specificRequest() {
        // 业务代码
    }
}
public class Adapter extends Adaptee implements Target {
    @Override
    public void request() {
        specificRequest();
    }
}

桥接模式

public interface Implementor {
    void operationImpl();
}
public abstract class Abstraction {
    protected Implementor impl;
    public void setImpl(Implementor impl) {
        this.impl = impl;
    }
    public abstract void operation();
}
public class RefinedAbstraction extends Abstraction {
    @Override
    public void operation() {
        impl.operationImpl();
    }
}
public class ConcreteImplementorA implements Implementor {
    @Override
    public void operationImpl() {
        // 具体实现
    }
}
public class ConcreteImplementorB implements Implementor {
    @Override
    public void operationImpl() {
        // 具体实现
    }
}

组合模式

public abstract class Component {
    protected String name;
    public Component(String name) {
        this.name = name;
    }
    public abstract void add(Component c);
    public abstract void remove(Component c);
    public abstract void display(int depth);
}
public class Composite extends Component {
    private List<Component> children = new ArrayList<Component>();
    public Composite(String name) {
        super(name);
    }
    @Override
    public void add(Component c) {
        children.add(c);
    }
    @Override
    public void remove(Component c) {
        children.remove(c);
    }
    @Override
    public void display(int depth) {
        System.out.println("-" * depth + name);
        for (Component component : children) {
            component.display(depth + 2);
        }
    }
}
public class Leaf extends Component {
    public Leaf(String name) {
        super(name);
    }
    @Override
    public void add(Component c) {
        System.out.println("Cannot add to a leaf");
    }
    @Override
    public void remove(Component c) {
        System.out.println("Cannot remove from a leaf");
    }
    @Override
    public void display(int depth) {
        System.out.println("-" * depth + name);
    }
}

装饰模式

public interface Component {
    void operation();
}
public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        // 具体操作
    }
}
public class Decorator implements Component {
    private Component component;
    public Decorator(Component component) {
        this.component = component;
    }
    @Override
    public void operation() {
        component.operation();
    }
}
public class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }
    @Override
    public void operation() {
        super.operation();
        addedFunction();
    }
    public void addedFunction() {
        // 新增功能
    }
}

外观模式

public class SubSystem1 {
    public void method1() {
        // 业务实现代码
    }
}
public class SubSystem2 {
    public void method2() {
        // 业务实现代码
    }
}
public class SubSystem3 {
    public void method3() {
        // 业务实现代码
    }
}
public class Facade {
    private SubSystem1 obj1 = new SubSystem1();
    private SubSystem2 obj2 = new SubSystem2();
    private SubSystem3 obj3 = new SubSystem3();
    public void method() {
        obj1.method1();
        obj2.method2();
        obj3.method3();
    }
}

享元模式

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 {
    private String allState;
    @Override
    public void operation() {
        // 具体操作
    }
}
public class FlyweightFactory {
    private Map<String, Flyweight> flyweights = new HashMap<String, Flyweight>();
    public Flyweight getFlyweight(String key) {
        Flyweight flyweight = (Flyweight) flyweights.get(key);
        if (flyweight != null) {
            System.out.println("具体享元" + key + "已经存在,被成功获取!");
        } else {
            flyweight = new ConcreteFlyweight(key);
            flyweights.put(key, flyweight);
        }
        return flyweight;
    }
}

代理模式

public interface Subject {
    void request();
}
public class RealSubject implements Subject {
    @Override
    public void request() {
        // 具体操作
    }
}
public class Proxy implements Subject {
    private RealSubject realSubject;
    @Override
    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        preRequest();
        realSubject.request();
        postRequest();
    }
    public void preRequest() {
        // 具体操作
    }
    public void postRequest() {
        // 具体操作
    }
}

责任链模式

public abstract class Handler {
    protected Handler successor;
    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }
    public abstract void handleRequest();
}
public class ConcreteHandler1 extends Handler {
    @Override
    public void handleRequest() {
        if (successor != null) {
            successor.handleRequest();
        } else {
            // 处理请求
        }
    }
}
public class ConcreteHandler2 extends Handler {
    @Override
    public void handleRequest() {
        if (successor != null) {
            successor.handleRequest();
        } else {
            // 处理请求
        }
    }
}

命令模式

public abstract class Command {
    protected Receiver receiver;
    public Command(Receiver receiver) {
        this.receiver = receiver;
    }
    public abstract void execute();
}
public class ConcreteCommand extends Command {
    public ConcreteCommand(Receiver receiver) {
        super(receiver);
    }
    @Override
    public void execute() {
        receiver.action();
    }
}
public class Invoker {
    private Command command;
    public void setCommand(Command command) {
        this.command = command;
    }
    public void executeCommand() {
        command.execute();
    }
}

迭代器模式

public interface Iterator {
    Object first();
    Object next();
    boolean hasNext();
}
public interface Aggregate {
    Iterator createIterator();
}
public class ConcreteIterator implements Iterator {
    private ConcreteAggregate aggregate;
    private int current = 0;
    public ConcreteIterator(ConcreteAggregate aggregate) {
        this.aggregate = aggregate;
    }
    @Override
    public Object first() {
        return aggregate.getItems().get(0);
    }
    @Override
    public Object next() {
        Object ret = null;
        current++;
        if (current < aggregate.count()) {
            ret = aggregate.getItems().get(current);
        }
        return ret;
    }
    @Override
    public boolean hasNext() {
        return current < aggregate.count();
    }
}
public class ConcreteAggregate implements Aggregate {
    private List<Object> items = new ArrayList<Object>();
    @Override
    public Iterator createIterator() {
        return new ConcreteIterator(this);
    }
    public int count() {
        return items.size();
    }
    public List<Object> getItems() {
        return items;
    }
    public void setItems(List<Object> items) {
        this.items = items;
    }
}

观察者模式

public interface Observer {
    void update();
}
public abstract class Subject {
    private List<Observer> observers = new ArrayList<Observer>();
    public void attach(Observer observer) {
        observers.add(observer);
    }
    public void detach(Observer observer) {
        observers.remove(observer);
    }
    public void notifyObservers() {
        for (Observer o : observers) {
            o.update();
        }
    }
}
public class ConcreteSubject extends Subject {
    private String subjectState;
    public String getSubjectState() {
        return subjectState;
    }
    public void setSubjectState(String subjectState) {
        this.subjectState = subjectState;
    }
}
public class ConcreteObserver implements Observer {
    private String name;
    private String observerState;
    private ConcreteSubject subject;
    public ConcreteObserver(ConcreteSubject subject, String name) {
        this.subject = subject;
        this.name = name;
    }
    @Override
    public void update() {
        observerState = subject.getSubjectState();
        System.out.println("观察者" + name + "的新状态是" + observerState);
    }
}

备忘录模式

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 String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public Memento createMemento() {
        return new Memento(state);
    }
    public void setMemento(Memento memento) {
        state = memento.getState();
    }
    public void showState() {
        System.out.println(state);
    }
}
public class Caretaker {
    private Memento memento;
    public Memento getMemento() {
        return memento;
    }
    public void setMemento(Memento memento) {
        this.memento = memento;
    }
}

状态模式

public abstract class State {
    public abstract void handle(Context context);
}
public class ConcreteStateA extends State {
    @Override
    public void handle(Context context) {
        context.setState(new ConcreteStateB());
    }
}
public class ConcreteStateB extends State {
    @Override
    public void handle(Context context) {
        context.setState(new ConcreteStateA());
    }
}
public class Context {
    private State state;
    public Context(State state) {
        this.state = state;
    }
    public void setState(State state) {
        this.state = state;
    }
    public void request() {
        state.handle(this);
    }
}