首页 > 其他分享 >设计模式:全网最全(23+10种)、最易懂(对比代码)、最简洁(三言两语)、最深度(带点评)的【设计模式】精华总结

设计模式:全网最全(23+10种)、最易懂(对比代码)、最简洁(三言两语)、最深度(带点评)的【设计模式】精华总结

时间:2024-05-31 11:29:25浏览次数:16  
标签:10 String 23 void private public 使用 设计模式 class

前言

设计模式是软件开发中的重要工具,灵活掌握大量的设计模式,能够帮助我们编写更灵活、可维护和可扩展的代码。网上有许多关于设计模式的文章,往往把设计模式介绍得高深莫测,墨守成规。于是,不久前萌发了写一篇简单易懂的设计模式介绍的文章的想法。

在开始之前,我想强调切勿滥用设计模式。在我的职业生涯中,遇到许多滥用设计模式的代码实现,这些滥用降低了项目代码可读性和可维护性。所以,我对设计模式的态度就是,思想要领要懂,优缺点要知,使用场景要准。

为了更好地直观展现各个设计模式的特点,示例代码中会提供“使用前”和“使用后”的对比,让读者更直观的看出设计模式的优劣。通过观察使用模式前和使用模式后的代码差异,从另一个角度掌握设计模式的本质。

文章写的过程比较断断续续,部分内容难免存在谬误,欢迎读者指正,共同进步。


经典的23种设计模式

首先,我们先从经典的23个设计模式入手,依次介绍:

创建型模式

  1. 工厂方法模式(Factory Method Pattern)

    • 基本概念:定义一个创建对象的接口,但由子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
    • 使用场景:当一个类不知道它所必须创建的对象的类时,或者一个类希望由它的子类来指定创建对象的类时。
    • 优点:代码解耦,增加新的产品类时不修改现有代码。
    • 缺点:增加复杂度,应用不当容易给人脱裤子放屁的感觉。
    // 使用前:
    class Product {};
    Product product = new Product();
    
    // 使用后:
    abstract class ProductFactory {
        abstract Product createProduct();
    }
    class ConcreteProductFactory extends ProductFactory {
        Product createProduct() {
            return new ConcreteProduct();
        }
    }
    
  2. 抽象工厂模式(Abstract Factory Pattern)

    • 基本概念:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
    • 使用场景:系统要独立于它的产品的创建、组合和表示时,系统中有多于一个的产品族,而系统只消费其中某一族的产品时。
    • 优点:分离接口和实现,产品族的扩展变得容易。
    • 缺点:有时真是多此一举。
    // 使用前:
    class ProductA {};
    class ProductB {};
    
    // 使用后:
    interface AbstractFactory {
        ProductA createProductA();
        ProductB createProductB();
    }
    class ConcreteFactory implements AbstractFactory {
        ProductA createProductA() {
            return new ConcreteProductA();
        }
        ProductB createProductB() {
            return new ConcreteProductB();
        }
    }
    
  3. 单例模式(Singleton Pattern)

    • 基本概念:确保一个类只有一个实例,并提供一个全局访问点。
    • 使用场景:当需要一个类只有一个实例,并且该实例需要被全局访问时。
    • 优点:控制实例数目,节省资源。
    • 缺点:大量的单例的析构顺序无法控制,而且,全局函数了解一下?啥?你用的是Java?好吧,要不考虑用Static方法。
    // 使用前:
    class Singleton {};
    
    // 使用后:
    class Singleton {
        private static Singleton instance;
        private Singleton() {}
        public static Singleton getInstance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
    
  4. 建造者模式(Builder Pattern)

    • 基本概念:将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
    • 使用场景:需要生成的产品对象有复杂的内部结构时,产品对象的属性相互依赖。
    • 优点:封装性好,构建和表示分离。
    • 缺点:使用不当时,多此一举。
    // 使用前:
    class Product {
        String partA;
        String partB;
    }
    Product product = new Product();
    product.partA = "A";
    product.partB = "B";
    
    // 使用后:
    class Product {
        String partA;
        String partB;
    }
    class ProductBuilder {
        private Product product = new Product();
        public ProductBuilder buildPartA(String partA) {
            product.partA = partA;
            return this;
        }
        public ProductBuilder buildPartB(String partB) {
            product.partB = partB;
            return this;
        }
        public Product getResult() {
            return product;
        }
    }
    
  5. 原型模式(Prototype Pattern)

    • 基本概念:用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
    • 使用场景:当一个系统应该独立于它的产品创建、构成和表示时,以及当要实例化的类是在运行时刻指定时。
    • 优点:性能提高,简化对象创建过程。
    • 缺点:每个类都需要实现克隆方法,复杂度增加,实现细节也被隐藏起来,代码隐晦。
    // 使用前:
    class Product {};
    
    // 使用后:
    abstract class Product implements Cloneable {
        abstract Product clone();
    }
    class ConcreteProduct extends Product {
        Product clone() {
            return new ConcreteProduct();
        }
    }
    

结构型模式

  1. 适配器模式(Adapter Pattern)

    • 基本概念:将一个类的接口转换成客户希望的另一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
    • 使用场景:系统需要使用现有的类,而此类的接口不符合系统的需求。
    • 优点:提高类的复用性。
    • 缺点:要是能直接用,谁能想出这主意。
    // 使用前:
    class Adaptee {
        void specificRequest() {}
    }
    
    // 使用后:
    interface Target {
        void request();
    }
    class Adapter implements Target {
        private Adaptee adaptee;
        Adapter(Adaptee adaptee) {
            this.adaptee = adaptee;
        }
        public void request() {
            adaptee.specificRequest();
        }
    }
    
  2. 装饰器模式(Decorator Pattern)

    • 基本概念:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰器模式相比生成子类更为灵活。是继承关系的一种替代方案。
    • 使用场景:需要动态地给一个对象增加功能,这些功能可以动态撤销。
    • 优点:可以代替继承扩展对象的功能。
    • 缺点:真的不能继承吗?要是基类重构了,你咋整?
    // 使用前:
    class Component {
        void operation() {}
    }
    
    // 使用后:
    abstract class Decorator extends Component {
        protected Component component;
        Decorator(Component component) {
            this.component = component;
        }
        void operation() {
            component.operation();
        }
    }
    class ConcreteDecorator extends Decorator {
        ConcreteDecorator(Component component) {
            super(component);
        }
        void operation() {
            super.operation();
            // additional behavior
        }
    }
    
  3. 代理模式(Proxy Pattern)

    • 基本概念:为其他对象提供一种代理以控制对这个对象的访问。
    • 使用场景:需要在访问对象时进行一些额外的操作,比如控制访问权限、延迟加载等。
    • 优点:控制对象的访问,引入一些策略,或者降低系统的复杂度。
    • 缺点:增加代码复杂度。
    // 使用前:
    class RealSubject {
        void request() {}
    }
    
    // 使用后:
    interface Subject {
        void request();
    }
    class Proxy implements Subject {
        private RealSubject realSubject;
        public void request() {
            if (realSubject == null) {
                realSubject = new RealSubject();
            }
            realSubject.request();
        }
    }
    
  4. 外观模式(Facade Pattern)

    • 基本概念:为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
    • 使用场景:系统有多个复杂的子系统,客户端需要与这些子系统交互时。
    • 优点:简化客户端接口,减少客户端与子系统之间的耦合。
    • 缺点:不符合开闭原则,修改外观类时可能影响子系统类。
    // 使用前:
    class Subsystem1 {
        void operation1() {}
    }
    class Subsystem2 {
        void operation2() {}
    }
    
    // 使用后:
    class Facade {
        private Subsystem1 subsystem1 = new Subsystem1();
        private Subsystem2 subsystem2 = new Subsystem2();
        public void operation() {
            subsystem1.operation1();
            subsystem2.operation2();
        }
    }
    
  5. 桥接模式(Bridge Pattern)

    • 基本概念:将抽象部分与它的实现部分分离,使它们都可以独立地变化。
    • 使用场景:需要在抽象和实现之间增加更多的灵活性时。
    • 优点:提高了系统的扩展性,解耦了抽象和实现。
    • 缺点:增加了系统的复杂性,没事别瞎用。
    // 使用前:
    class Abstraction {
        void operation() {}
    }
    
    // 使用后:
    interface Implementor {
        void operationImpl();
    }
    class ConcreteImplementorA implements Implementor {
        public void operationImpl() {
            // Implementation A
        }
    }
    class ConcreteImplementorB implements Implementor {
        public void operationImpl() {
            // Implementation B
        }
    }
    abstract class Abstraction {
        protected Implementor implementor;
        Abstraction(Implementor implementor) {
            this.implementor = implementor;
        }
        abstract void operation();
    }
    class RefinedAbstraction extends Abstraction {
        RefinedAbstraction(Implementor implementor) {
            super(implementor);
        }
        void operation() {
            implementor.operationImpl();
        }
    }
    
  6. 组合模式(Composite Pattern)

    • 基本概念:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
    • 使用场景:需要表示对象的部分-整体层次结构时,希望用户忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时。
    • 优点:使得用户可以一致地使用组合结构和单个对象。
    • 缺点:使设计变得更加复杂,要是没人拿枪指着你,别用。
    // 使用前:
    class Leaf {
        void operation() {}
    }
    
    // 使用后:
    interface Component {
        void operation();
    }
    class Leaf implements Component {
        public void operation() {
            // Leaf operation
        }
    }
    class Composite implements Component {
        private List<Component> children = new ArrayList<>();
        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);
        }
    }
    
  7. 享元模式(Flyweight Pattern)

    • 基本概念:运用共享技术有效地支持大量细粒度的对象。
    • 使用场景:系统中有大量相似对象,导致内存开销过大时。
    • 优点:减少对象的创建,降低内存消耗。
    • 缺点:使系统更加复杂,需要分离出外部状态和内部状态。对多线程开发不利,不利于高并发场景。
    // 使用前:
    class BigObject {
        private String state;
    }
    
    // 使用后:
    interface Flyweight {
        void operation(String extrinsicState);
    }
    class ConcreteFlyweight implements Flyweight {
        private String intrinsicState;
        public void operation(String extrinsicState) {
            // Use intrinsicState and extrinsicState
        }
    }
    class FlyweightFactory {
        private Map<String, Flyweight> flyweights = new HashMap<>();
        public Flyweight getFlyweight(String key) {
            if (!flyweights.containsKey(key)) {
                flyweights.put(key, new ConcreteFlyweight());
            }
            return flyweights.get(key);
        }
    }
    

行为型模式

  1. 策略模式(Strategy Pattern)

    • 基本概念:定义一系列算法,将每一个算法封装起来,并且使它们可以互换。
    • 使用场景:系统有多个算法可以使用,并且需要在运行时决定使用哪一个算法。
    • 优点:算法可以自由切换,扩展性好。
    • 缺点:我干嘛呆着没事搞那么多类呢,不“面向对象”难道还不活了?switch-case用过吗?
    // 使用前:
    class Context {
        void algorithm() {
            // Algorithm implementation
        }
    }
    
    // 使用后:
    interface Strategy {
        void algorithm();
    }
    class ConcreteStrategyA implements Strategy {
        public void algorithm() {
            // Algorithm A implementation
        }
    }
    class ConcreteStrategyB implements Strategy {
        public void algorithm() {
            // Algorithm B implementation
        }
    }
    class Context {
        private Strategy strategy;
        Context(Strategy strategy) {
            this.strategy = strategy;
        }
        void executeStrategy() {
            strategy.algorithm();
        }
    }
    
  2. 模板方法模式(Template Method Pattern)

    • 基本概念:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
    • 使用场景:需要在某些步骤中使用不同的实现,但整体算法结构固定时。
    • 优点:提高代码复用性,灵活性好。
    • 缺点:类的数目增加,增加了系统的复杂性。打破了自顶向下阅读代码的习惯,看代码时容易蛋疼。
    // 使用前:
    class Algorithm {
        void step1() {}
        void step2() {}
        void step3() {}
    }
    
    // 使用后:
    abstract class AbstractClass {
        public final void templateMethod() {
            step1();
            step2();
            step3();
        }
        abstract void step1();
        abstract void step2();
        abstract void step3();
    }
    class ConcreteClass extends AbstractClass {
        void step1() {
            // Step 1 implementation
        }
        void step2() {
            // Step 2 implementation
        }
        void step3() {
            // Step 3 implementation
        }
    }
    
  3. 观察者模式(Observer Pattern)

    • 基本概念:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
    • 使用场景:一个对象的改变需要通知其他对象,而不希望这些对象紧密耦合时。
    • 优点:降低了对象之间的耦合度,可以轻松实现依赖倒置。
    • 缺点:按需使用就好,没啥缺点。
    // 使用前:
    class Subject {
        void notifyObservers() {}
    }
    
    // 使用后:
    interface Observer {
        void update();
    }
    class ConcreteObserver implements Observer {
        public void update() {
            // Observer update implementation
        }
    }
    class Subject {
        private List<Observer> observers = new ArrayList<>();
        public void addObserver(Observer observer) {
            observers.add(observer);
        }
        public void removeObserver(Observer observer) {
            observers.remove(observer);
        }
        public void notifyObservers() {
            for (Observer observer : observers) {
                observer.update();
            }
        }
    }
    
  4. 迭代子模式(Iterator Pattern)

    • 基本概念:提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。
    • 使用场景:需要访问一个聚合对象的内容而不暴露其内部表示时。
    • 优点:支持以不同的方式遍历一个聚合对象。
    • 缺点:C++的STL采用的模式,还行吧,近些年吹的人好像变少了。
    // 使用前:
    class Collection {
        void get(int index) {}
    }
    
    // 使用后:
    interface Iterator {
        boolean hasNext();
        Object next();
    }
    class ConcreteIterator implements Iterator {
        private List<Object> items;
        private int position = 0;
        ConcreteIterator(List<Object> items) {
            this.items = items;
        }
        public boolean hasNext() {
            return position < items.size();
        }
        public Object next() {
            return items.get(position++);
        }
    }
    class Collection {
        private List<Object> items = new ArrayList<>();
        public Iterator createIterator() {
            return new ConcreteIterator(items);
        }
    }
    
  5. 责任链模式(Chain of Responsibility Pattern)

    • 基本概念:为解除请求的发送者和接收者之间的耦合,使多个对象都有机会处理这个请求,将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。
    • 使用场景:有多个对象可以处理同一个请求时,具体哪个对象处理该请求由运行时刻自动确定。
    • 优点:降低了对象之间的耦合度,便于扩展。
    • 缺点:用的挺广,场景比较固定,按需使用即可。
    // 使用前:
    class Handler {
        void handleRequest() {}
    }
    
    // 使用后:
    abstract class Handler {
        protected Handler successor;
        public void setSuccessor(Handler successor) {
            this.successor = successor;
        }
        public abstract void handleRequest();
    }
    class ConcreteHandler1 extends Handler {
        public void handleRequest() {
            if (/* some condition */) {
                // handle request
            } else if (successor != null) {
                successor.handleRequest();
            }
        }
    }
    class ConcreteHandler2 extends Handler {
        public void handleRequest() {
            if (/* some condition */) {
                // handle request
            } else if (successor != null) {
                successor.handleRequest();
            }
        }
    }
    
  6. 命令模式(Command Pattern)

    • 基本概念:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。
    • 使用场景:需要对行为进行参数化、排队、记录日志、支持撤销和恢复操作时。
    • 优点:降低系统耦合度,增加新的命令容易。
    • 缺点:其实,switch-case也能实现。
    // 使用前:
    class Command {
        void openTheDoor() {}
    }
    
    // 使用后:
    interface Command {
        void execute();
    }
    class OpenTheDoorCommand implements Command {
        private Door door;
        OpenTheDoorCommand(Door door) {
            this.door = door;
        }
        public void execute() {
            door.open();
        }
    }
    class Door {
        void open() {
            // open the door
        }
    }
    class Invoker {
        private Command command;
        public void setCommand(Command command) {
            this.command = command;
        }
        public void executeCommand() {
            command.execute();
        }
    }
    
  7. 备忘录模式(Memento Pattern)

    • 基本概念:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便以后恢复对象到原先保存的状态。
    • 使用场景:需要保存和恢复对象的状态时。
    • 优点:保存状态时不破坏封装性,本质是按功能划分类的思想,把序列化的逻辑抽离出来。
    • 缺点:目标对象重构了咋办?强相关逻辑的代码分散开,不利于阅读和管理。
    // 使用前:
    class Originator {
        private String state;
        public void setState(String state) {
            this.state = state;
        }
        public String getState() {
            return state;
        }
    }
    
    // 使用后:
    class Memento {
        private String state;
        Memento(String state) {
            this.state = state;
        }
        public String getState() {
            return state;
        }
    }
    class Originator {
        private String state;
        public void setState(String state) {
            this.state = state;
        }
        public Memento saveStateToMemento() {
            return new Memento(state);
        }
        public void getStateFromMemento(Memento memento) {
            state = memento.getState();
        }
    }
    class Caretaker {
        private List<Memento> mementoList = new ArrayList<>();
        public void add(Memento state) {
            mementoList.add(state);
        }
        public Memento get(int index) {
            return mementoList.get(index);
        }
    }
    
  8. 状态模式(State Pattern)

    • 基本概念:允许对象在其内部状态改变时改变它的行为,对象看起来好像修改了它的类。
    • 使用场景:对象的行为依赖于它的状态,并且它必须在运行时刻根据状态改变它的行为时。
    • 优点:将状态的行为局部化,并将不同状态的行为分割开来。本质也是按功能划分类的思想,把相对独立相关的逻辑抽象并抽离出来。
    • 缺点:可能会导致状态类数量增加,对于简单场景来说,没必要弄这么复杂。
    // 使用前:
    class Context {
        void request() {
            // handle request based on state
        }
    }
    
    // 使用后:
    interface State {
        void handle(Context context);
    }
    class ConcreteStateA implements State {
        public void handle(Context context) {
            // handle request in state A
        }
    }
    class ConcreteStateB implements State {
        public void handle(Context context) {
            // handle request in state B
        }
    }
    class Context {
        private State state;
        public void setState(State state) {
            this.state = state;
        }
        public void request() {
            state.handle(this);
        }
    }
    
  9. 访问者模式(Visitor Pattern)

    • 基本概念:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
    • 使用场景:需要对一个对象结构中的对象进行很多不同的操作,而又不希望这些操作“污染”对象的类时。
    • 优点:增加新的操作很容易,不需要对原始对象进行修改。
    • 缺点:增加新的元素困难,需要修改多处代码,一般用于操作很多但元素相对固定的场景。
   // 使用前:
   class Element {
       void operation() {}
   }

   // 使用后:
   interface Visitor {
       void visit(ElementA element);
       void visit(ElementB element);
   }
   interface Element {
       void accept(Visitor visitor);
   }
   class ElementA implements Element {
       public void accept(Visitor visitor) {
           visitor.visit(this);
       }
   }
   class ElementB implements Element {
       public void accept(Visitor visitor) {
           visitor.visit(this);
       }
   }

   class ConcreteVisitor implements Visitor {
       public void visit(ElementA element) {
           // operation on ElementA
       }
       public void visit(ElementB element) {
           // operation on ElementB
       }
   }
  1. 中介者模式(Mediator Pattern)

    • 基本概念:用一个中介对象来封装一系列对象的交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
    • 使用场景:多个对象之间存在复杂的引用关系,导致系统结构混乱且难以复用时。
    • 优点:降低了对象之间的耦合度,使得对象之间的交互变得简单。
    • 缺点:中介者会膨胀得很大,变得复杂难以维护。本质上是将一种复杂的逻辑从各处单独抽离,并将这些逻辑组合成为一个具体类的做法。下面的例子展示了其中一种具体的抽离方法,但实践中不要局限这一种。
    // 使用前:
    class Colleague {
        void send() {}
        void receive() {}
    }
    // 使用后:
    // 中介者接口(Mediator):定义了同事对象到中介者对象的接口,用于各同事对象通知中介者。
    interface Mediator {
        void send(String message, Colleague colleague);
    }
    // 具体中介者(Concrete Mediator):实现中介者接口,并协调各同事对象之间的交互。
    class ConcreteMediator implements Mediator {
        private Colleague1 colleague1;
        private Colleague2 colleague2;
        public void setColleague1(Colleague1 colleague1) {
            this.colleague1 = colleague1;
        }
        public void setColleague2(Colleague2 colleague2) {
            this.colleague2 = colleague2;
        }
        public void send(String message, Colleague colleague) {
            if (colleague == colleague1) {
                colleague2.receive(message);
            } else {
                colleague1.receive(message);
            }
        }
    }
    // 同事类(Colleague):所有同事类的接口。每个同事只知道自己的行为,而不了解其他同事的情况,但它们知道中介者。
    
    abstract class Colleague {
        protected Mediator mediator;
        public Colleague(Mediator mediator) {
            this.mediator = mediator;
        }
    }
    class Colleague1 extends Colleague {
        public Colleague1(Mediator mediator) {
            super(mediator);
        }
        public void send(String message) {
            mediator.send(message, this);
        }
        public void receive(String message) {
            // handle message
        }
    }
    class Colleague2 extends Colleague {
        public Colleague2(Mediator mediator) {
            super(mediator);
        }
        public void send(String message) {
            mediator.send(message, this);
        }
        public void receive(String message) {
            // handle message
        }
    }
    
  2. 解释器模式(Interpreter Pattern)

    • 基本概念:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
    • 使用场景:当有一个语言需要解释执行,并且你可以将该语言中的句子表示为一个抽象语法树时。
    • 优点:容易扩展文法,改变和扩展文法都很容易。
    • 缺点:对于复杂的文法,解释器模式会导致类层次结构变得复杂。但是确实将每一个文法逻辑单独抽离出来,使得每个文法便于维护。这个模式在编译器的语法解析中广泛使用。
    // 使用前:
    class Context {
        void interpret(String expression) {
            // interpret expression
        }
    }
    
    // 使用后:
    interface Expression {
        boolean interpret(String context);
    }
    class TerminalExpression implements Expression {
        private String data;
        public TerminalExpression(String data) {
            this.data = data;
        }
        public boolean interpret(String context) {
            return context.contains(data);
        }
    }
    class OrExpression implements Expression {
        private Expression expr1;
        private Expression expr2;
        public OrExpression(Expression expr1, Expression expr2) {
            this.expr1 = expr1;
            this.expr2 = expr2;
        }
        public boolean interpret(String context) {
            return expr1.interpret(context) || expr2.interpret(context);
        }
    }
    class AndExpression implements Expression {
        private Expression expr1;
        private Expression expr2;
        public AndExpression(Expression expr1, Expression expr2) {
            this.expr1 = expr1;
            this.expr2 = expr2;
        }
        public boolean interpret(String context) {
            return expr1.interpret(context) && expr2.interpret(context);
        }
    }
    // class OhterExpression ....
    

其他常见的设计模式

除了以上列出的经典的23种设计模式,还有一些其他的著名的设计模式,我们对设计模式的态度是掌握其核心精髓,但不照搬。所以,多了解一些设计模式,还是非常有用的。
于是笔者额外选出了10个常见的设计模式加以介绍。

其他设计模式

  1. 空对象模式(Null Object Pattern)

    • 基本概念:使用一个空对象代替 null,以避免 null 引用的检查和处理。
    • 使用场景:需要避免多次检查 null,并希望使用一个默认的行为时。
    • 优点:简化代码,减少 null 检查。
    • 缺点:需要额外创建空对象类。大部分场景下都可以在初始化的适合给个默认值,这个设计模式仅用于无法给默认值,并且出现了大量的判空逻辑才考虑使用。实际项目中很少用得上,特别是空安全语言出来之后。
    // 使用前:
    class Customer {
        String name;
        public String getName() {
            return name;
        }
    }
    
    // 使用后:
    abstract class AbstractCustomer {
        protected String name;
        public abstract boolean isNil();
        public abstract String getName();
    }
    class RealCustomer extends AbstractCustomer {
        public RealCustomer(String name) {
            this.name = name;
        }
        public boolean isNil() {
            return false;
        }
        public String getName() {
            return name;
        }
    }
    class NullCustomer extends AbstractCustomer {
        public boolean isNil() {
            return true;
        }
        public String getName() {
            return "Not Available";
        }
    }
    
  2. 对象池模式(Object Pool Pattern)

    • 基本概念:维护一个对象池,以重复使用对象,避免频繁创建和销毁对象。
    • 使用场景:需要频繁创建和销毁对象时,尤其是创建和销毁开销较大时。
    • 优点:减少了对象创建和销毁的开销,提升系统性能。
    • 缺点:需要维护对象池的生命周期,增加复杂度。不过这个设计模式其实挺常见的,例如线程池。
    // 使用前:
    class ExpensiveObject {
        public ExpensiveObject() {
            // Expensive initialization
        }
    }
    
    // 使用后:
    class ObjectPool {
        private List<ExpensiveObject> available = new ArrayList<>();
        private List<ExpensiveObject> inUse = new ArrayList<>();
    
        public ExpensiveObject acquire() {
            if (available.isEmpty()) {
                available.add(new ExpensiveObject());
            }
            ExpensiveObject instance = available.remove(available.size() - 1);
            inUse.add(instance);
            return instance;
        }
    
        public void release(ExpensiveObject instance) {
            inUse.remove(instance);
            available.add(instance);
        }
    }
    
  3. 数据访问对象模式(DAO Pattern)

    • 基本概念:提供一种抽象接口,以便对数据库或其他持久化存储进行访问和操作。
    • 使用场景:需要与数据库或其他持久化存储交互时。
    • 优点:分离数据访问逻辑和业务逻辑,提高代码的可维护性和可测试性。
    • 缺点:需要额外的类和接口,增加了系统的复杂度。经常用数据库的话对这个模式一定不陌生。
    // 使用前:
    class User {
        private int id;
        private String name;
    }
    
    // 使用后:
    interface UserDao {
        void save(User user);
        User findById(int id);
    }
    class UserDaoImpl implements UserDao {
        public void save(User user) {
            // Save user to database
        }
        public User findById(int id) {
            // Find user by id from database
            return new User();
        }
    }
    
  4. 服务定位器模式(Service Locator Pattern)

    • 基本概念:使用服务定位器来提供依赖注入的功能,动态查找和获取服务实例。
    • 使用场景:需要动态查找和获取服务实例时。
    • 优点:降低客户端与服务实现之间的耦合度。
    • 缺点:隐藏了类之间的依赖关系,可能导致难以理解和调试。
    // 使用前:
    class Service {
        void execute() {}
    }
    
    // 使用后:
    interface Service {
        void execute();
    }
    class ServiceA implements Service {
        public void execute() {
            // Service A implementation
        }
    }
    class ServiceLocator {
        private static Map<String, Service> cache = new HashMap<>();
        public static Service getService(String serviceName) {
            Service service = cache.get(serviceName);
            if (service == null) {
                // Lookup and create service
                service = new ServiceA();
                cache.put(serviceName, service);
            }
            return service;
        }
    }
    
  5. 拦截过滤器模式(Intercepting Filter Pattern)

    • 基本概念:使用过滤器来对请求进行预处理和后处理。
    • 使用场景:需要对请求进行预处理和后处理时。
    • 优点:灵活地对请求进行处理,解耦请求处理逻辑。
    • 缺点:增加了系统的复杂度。一般用于逻辑结构比较固定,行为变化或扩展比较频繁的场景。
    // 使用前:
    class RequestHandler {
        void handleRequest() {
            // Handle request
        }
    }
    
    // 使用后:
    interface Filter {
        void execute(String request);
    }
    class AuthenticationFilter implements Filter {
        public void execute(String request) {
            // Authentication logic
        }
    }
    class DebugFilter implements Filter {
        public void execute(String request) {
            // Debug logic
        }
    }
    class FilterChain {
        private List<Filter> filters = new ArrayList<>();
        private Target target;
    
        public void addFilter(Filter filter) {
            filters.add(filter);
        }
        public void execute(String request) {
            for (Filter filter : filters) {
                filter.execute(request);
            }
            target.execute(request);
        }
    }
    class Target {
        public void execute(String request) {
            // Handle request
        }
    }
    class FilterManager {
        private FilterChain filterChain;
    
        public FilterManager(Target target) {
            filterChain = new FilterChain();
            filterChain.setTarget(target);
        }
        public void addFilter(Filter filter) {
            filterChain.addFilter(filter);
        }
        public void filterRequest(String request) {
            filterChain.execute(request);
        }
    }
    
  6. 前端控制器模式(Front Controller Pattern)

    • 基本概念:提供一个统一的入口点,用于处理所有的请求。
    • 使用场景:需要一个统一的请求处理入口时。
    • 优点:集中控制请求处理,简化请求处理逻辑。
    • 缺点:增加了系统的复杂度。对外接口的整洁度高了,但把脏活累活藏到FrontController 里了。
    // 使用前:
    class Dispatcher {
        void dispatch(String request) {
            // Dispatch request
        }
    }
    
    // 使用后:
    class FrontController {
        private Dispatcher dispatcher;
    
        public FrontController() {
            dispatcher = new Dispatcher();
        }
        private boolean isAuthenticUser() {
            // Authentication logic
            return true;
        }
        private void trackRequest(String request) {
            // Request tracking logic
        }
        public void dispatchRequest(String request) {
            trackRequest(request);
            if (isAuthenticUser()) {
                dispatcher.dispatch(request);
            }
        }
    }
    
  7. 业务代表模式(Business Delegate Pattern)

    • 基本概念:主要用于简化表示层(如用户界面)与业务层(如EJBs、Web服务等)之间的交互,并降低它们之间的耦合度。这种模式通过引入一个中间层(即业务代表)来封装对业务服务的访问细节,使得表示层可以以一种统一且抽象的方式与业务逻辑交互,而无需直接了解底层业务服务的技术细节或复杂性。
    • 使用场景:需要对业务服务进行封装,以简化客户端访问时。
    • 优点:简化客户端代码,降低客户端与业务服务之间的耦合度。
    • 缺点:增加了系统的复杂度。看起来概念很多,其实这个设计模式没啥好细看的,和与代理模式、外观模式、服务定位器模式和依赖注入模式大同小异,都是把一些复杂的功能包装起来实现对使用者(调用方)更友好的目标。
    // 使用前:
    class BusinessService {
        void doProcessing() {}
    }
    
    // 使用后:
    interface BusinessService {
        void doProcessing();
    }
    class EJBService implements BusinessService {
        public void doProcessing() {
            // EJB service processing
        }
    }
    class BusinessDelegate {
        private BusinessService businessService;
        private String serviceType;
    
        public void setServiceType(String serviceType) {
            this.serviceType = serviceType;
        }
        public void doTask() {
            if (serviceType.equalsIgnoreCase("EJB")) {
                businessService = new EJBService();
            }
            businessService.doProcessing();
        }
    }
    
  8. 双重检查锁模式(Double-Checked Locking Pattern)

    • 基本概念:在多线程环境中,减少锁的开销,通过双重检查来确保只在第一次创建对象时加锁。
    • 使用场景:需要在多线程环境中安全地延迟初始化对象时。最早就是从单例模式中衍生出来的模式。
    • 优点:提高了性能,减少了不必要的同步开销。
    • 缺点:代码复杂度增加,容易出错。本质上可能不算是一个设计模式,是多线程编程中带来的额外心智负担引入的一种常见做法。
    // 使用前:
    class Singleton {
        private static Singleton instance;
        public static synchronized Singleton getInstance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }
    
    // 使用后:
    class Singleton {
        private volatile static Singleton instance;
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
    
  9. MVC模式(Model-View-Controller Pattern)

    • 基本概念:将应用程序分为三个部分:模型(Model)、视图(View)和控制器(Controller)。模型表示应用程序的核心数据和业务逻辑,视图负责显示数据,控制器处理用户输入。
    • 使用场景:需要分离数据和业务逻辑与显示和输入处理时。
    • 优点:分离关注点,提高代码的可维护性和可测试性。
    • 缺点:增加了系统的复杂度。本质上是将代码结构中“变”与“不变”的部分分离开来。一般认为View是经常变的,而Model是较少改变的。MVC模式非常老,早在1980年代就出现了。随着现代图形界面框架的成熟,这种设计模式更多的变成了一种指导思想,不适合生搬硬套。
    // 使用前:
    class Application {
        void display() {}
        void handleInput() {}
    }
    
    // 使用后:
    class Model {
        private String data;
        public String getData() {
            return data;
        }
        public void setData(String data) {
            this.data = data;
        }
    }
    class View {
        public void display(String data) {
            // Display data
        }
    }
    class Controller {
        private Model model;
        private View view;
        public Controller(Model model, View view) {
            this.model = model;
            this.view = view;
        }
        public void updateView() {
            view.display(model.getData());
        }
        public void setModelData(String data) {
            model.setData(data);
        }
    }
    
  10. 职责链模式(Chain of Responsibility Pattern)

    • 基本概念:为解除请求的发送者和接收者之间的耦合,使多个对象都有机会处理这个请求,将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。
    • 使用场景:有多个对象可以处理同一个请求时,具体哪个对象处理该请求由运行时刻自动确定。
    • 优点:降低了对象之间的耦合度。
    • 缺点:可能会导致请求处理耗时增加。不过其实也挺常见的。以下代码不必深入研究,职责链的实现方式有很多种,这种示例代码只是展示了其中一种最简单的。
    // 使用前:
    class Handler {
        void handleRequest() {}
    }
    
    // 使用后:
    abstract class Handler {
        protected Handler successor;
        public void setSuccessor(Handler successor) {
            this.successor = successor;
        }
        public abstract void handleRequest();
    }
    class ConcreteHandler1 extends Handler {
        public void handleRequest() {
            if (/* some condition */) {
                // handle request
            } else if (successor != null) {
                successor.handleRequest();
            }
        }
    }
    class ConcreteHandler2 extends Handler {
        public void handleRequest() {
            if (/* some condition */) {
                // handle request
            } else if (successor != null) {
                successor.handleRequest();
            }
        }
    }
    

结语

设计模式真要仔细列出来,其实是列不完的。但是你会发现许多设计模式的相似度很高,所以继续列下去其实已经没什么价值了。无论什么设计模式,其实都是为了解决某个问题从而放弃了直观和简洁的代码,这种付出在一些场景是合适的,但是判断哪些场景合适,就需要大家不断实践和积累了。
设计模式虽然多,但万变不离其宗,了解其思想,吸收其精华,不拘泥于具体模式,追求达到无招胜有招的境地。
看到这里,最后再叮嘱一句,我们在开发时需要从实际需求出发,不拘泥于具体的某个设计模式,往往用直接了当,高效,简洁的代码实现功能,避免过度设计,才是最优选择。

标签:10,String,23,void,private,public,使用,设计模式,class
From: https://blog.csdn.net/hebhljdx/article/details/139330971

相关文章

  • 谈判专家迅雷BT下载[WAV/2.12GB/5.36GB]高清版画质[HD720p/1080p]
    电影《谈判专家》是一部以谈判为主题的悬疑犯罪片。该片由中国导演导演,于年上映。本片以充满智慧和心计的谈判专家为主角,讲述了他在一场看似无解的罪案谈判中的精彩对决。这部电影引人入胜、紧张刺激,给观众们带来了一场智力与才智之间的较量。 电影中的主角是一位......
  • Centos8安装k8s1.23.9
    离线安装一、环境准备卸载podman关闭交换区禁用selinux关闭防火墙依赖包安装系统参数优化配置本地dockeryum源一:centos8默认安装podmanbuildah需要卸载sudoyumerasepodmanbuildah-y二:节点关闭swap分区swapoff-a&&sysctl-wvm.swappiness=0sudosed-i'......
  • pcm5102芯片接口音频格式简析
    1.I2S,leftjustified中文,左对齐(MSB)标准,和stm32的SAI_I2S_MSBJUSTIFIED格式对应:具体含义:在LRCLK发生翻转的同时开始传输数据。该标准较少使用。注意此时LRCLK为1时,传输的是左声道数据,这刚好与I2SPhilips标准相反。左对齐(MSB)标准时序图如下所示:  ......
  • Centos7部署k8s1.23.9
    !/bin/bashfunctionnode_update_kernel(){启用ELRepo仓库sudorpm--importhttps://www.elrepo.org/RPM-GPG-KEY-elrepo.orgsudorpm-Uvhhttp://www.elrepo.org/elrepo-release-7.0-6.el7.elrepo.noarch.rpm查看可用的系统内核包sudoyum--disablerepo="*"--enabl......
  • 麒麟kylin安装K8s1.23.9
    1.主机名解析10.129.148.4hangkong-k8s-node0110.129.148.5hangkong-k8s-node0210.129.148.6hangkong-k8s-node0310.129.148.4hangkong-k8s.vip.com2.主机名设置echo'hangkong-k8s-node01'>/etc/hostnameecho'hangkong-k8s-node02'>/etc/hos......
  • 麒麟kylin-ARM安装K8s1.23.9
    第一章k8s及中间件安装1.主机名解析2.主机名设置3.禁用iptables和firewalld4.禁用selinux(linux下的一个安全服务,必须禁用)5.禁用swap分区(主要是注释最后一行)6.修改系统的内核参数7.配置ipvs功能8.安装docker验证docker安装是否成功9.安装kubernetes1.23.910.集群初始......
  • Leetcode 力扣106. 从中序与后序遍历序列构造二叉树 (抖音号:708231408)
    给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。示例1:输入:inorder=[9,3,15,20,7],postorder=[9,15,7,20,3]输出:[3,9,20,null,null,15,7]示例2:输入:inorder=[......
  • Leetcode 力扣105. 从前序与中序遍历序列构造二叉树 (抖音号:708231408)
    给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。示例1:输入:preorder=[3,9,20,15,7],inorder=[9,3,15,20,7]输出:[3,9,20,null,null,15,7]示例2:输入:preorder......
  • Delphi 2010 新增功能之: IOUtils 单元(1): 初识 TDirectory.GetFiles
    用IOUtils单元下的TDirectory.GetFiles获取文件列表太方便了;下面的例子只是TDirectory.GetFiles的典型应用...unitUnit1;interfaceuses Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms, Dialogs,StdCtrls;type TForm1=......
  • 【Yarn】yarn logs 日志过大 The total log size is too large The log size limit is
    1.概述今天要排查一个现场,然后需要下载日志查看,结果发现日志过大,无法下载[mr@cqsec10075~]$yarnlogs-applicationIdapplication_1679365191066_0008>aa.txt2023-03-2814:24:42......