略读设计模式(六)

状态模式:

abstract class State {
    public abstract void handle();
}

class ConcreteState extends State {
    public void handle() {
    }
}

class Context {
    private State state;
    private int value;
    public void setState(State state) {
        this.state = state;
    }
    public void request() {
        state.handle();
    }
}

策略模式:

abstract class AbstractStrategy {
    public abstract void algorithm();
}
class ConcreteStrategyA extends AbstractStrategy {
    public void algorithm() {
    }
}

class Context {
    private AbstractStrategy strategy;
    public void setStrategy(AbstractStrategy strategy) {
        this.strategy = strategy;
    }
    public void algorithm() {
        strategy.algorithm();
    }
}

模板模式:

abstract class AbstractClass {
    public void TemplateMethod() {
        PrimitiveOperation1();
        PrimitiveOperation2();
        PrimitiveOperation3();
    }
    public void PrimitiveOperation1() {
    }
    public  abstract    void    PrimitiveOperation2();
    public virtual void PrimitiveOperation3() {
    }
}


class ConcreteClass extends AbstractClass {
    @Override
    public void PrimitiveOperation2() {
    }
    @Override
    public void PrimitiveOperation3() {
    }
}

访问者模式:

abstract class Visitor {
    public abstract void visit(ConcreteElementA elementA);
    public abstract void visit(ConcreteElementB elementB);
    public void visit(ConcreteElementC elementC) {
    }
}
class ConcreteVisitor extends Visitor {
    public void visit(ConcreteElementA elementA) {
    }
    public void visit(ConcreteElementB elementB) {
    }
}

interface Element {
    public void accept(Visitor visitor);
}

class ConcreteElementA implements Element {
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
    public void operationA() {
    }
}

书籍地址:https://gof.quanke.name/

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据