常见的23种设计模式和七大设计模式原则,一篇文章就搞定了!

在软件开发中,设计模式是一种经过验证的解决方案,它可以帮助开发人员更好地组织和编写代码。设计模式不仅可以提高代码的可读性和可维护性,还可以加速软件开发的进程。

本文将介绍常见的23种设计模式和七大设计模式原则,并对每个模式进行详细解释和示例代码演示。

23种设计模式

创建型模式

创建型模式关注对象的创建过程,包括简单工厂模式、工厂方法模式、抽象工厂模式、单例模式、建造者模式和原型模式。

  1. 简单工厂模式

简单工厂模式通过一个工厂类来创建对象,隐藏了对象创建的细节,并提供了统一的接口,让客户端无需知道具体的实现方式。

public class SimpleFactory {
    
    
    public static Product createProduct(String type) {
    
    
        if (type.equals("A")) {
    
    
            return new ConcreteProductA();
        } else if (type.equals("B")) {
    
    
            return new ConcreteProductB();
        } else {
    
    
            throw new IllegalArgumentException("Invalid product type: " + type);
        }
    }
}
  1. 工厂方法模式

工厂方法模式将对象的创建延迟到子类中处理,通过让子类决定如何创建对象来解耦合。

public abstract class Creator {
    
    
    public abstract Product createProduct();
}

public class ConcreteCreatorA extends Creator {
    
    
    public Product createProduct() {
    
    
        return new ConcreteProductA();
    }
}

public class ConcreteCreatorB extends Creator {
    
    
    public Product createProduct() {
    
    
        return new ConcreteProductB();
    }
}
  1. 抽象工厂模式

抽象工厂模式提供一个接口,用于创建相关的一系列产品,而不需要指定具体的实现类。它将工厂方法模式扩展到了多个产品系列上。

public interface AbstractFactory {
    
    
    ProductA createProductA();
    ProductB createProductB();
}

public class ConcreteFactory1 implements AbstractFactory {
    
    
    public ProductA createProductA() {
    
    
        return new ConcreteProductA1();
    }

    public ProductB createProductB() {
    
    
        return new ConcreteProductB1();
    }
}

public class ConcreteFactory2 implements AbstractFactory {
    
    
    public ProductA createProductA() {
    
    
        return new ConcreteProductA2();
    }

    public ProductB createProductB() {
    
    
        return new ConcreteProductB2();
    }
}
  1. 单例模式

单例模式保证一个类只有一个实例,并提供了一个全局访问点,让其他对象可以访问该实例。

public class Singleton {
    
    
    private static Singleton instance;

    private Singleton() {
    
    }

    public static synchronized Singleton getInstance() {
    
    
        if (instance == null) {
    
    
            instance = new Singleton();
        }
        return instance;
    }
}
  1. 建造者模式

建造者模式将一个复杂对象的创建过程拆分成多个简单的步骤,不同的建造者可以利用这些步骤来构建不同的对象。

public class Product {
    
    
    private String part1;
    private String part2;

    public void setPart1(String part1) {
    
    
        this.part1 = part1;
    }

    public void setPart2(String part2) {
    
    
        this.part2 = part2;
    }
}

public abstract class AbstractBuilder {
    
    
    protected Product product = new Product();

    public abstract void buildPart1();
    public abstract void buildPart2();

    public Product getResult() {
    
    
        return product;
    }
}

public class ConcreteBuilder extends AbstractBuilder {
    
    
    public void buildPart1() {
    
    
        product.setPart1("Part 1");
    }

    public void buildPart2() {
    
    
        product.setPart2("Part 2");
    }
}

public class Director {
    
    
    private AbstractBuilder builder;

    public Director(AbstractBuilder builder) {
    
    
        this.builder = builder;
    }

    public void buildProduct() {
    
    
        builder.buildPart1();
        builder.buildPart2();
    }
}
  1. 原型模式

原型模式通过指定一种原型对象来创建新的对象,并且可以通过克隆来创建新的对象。

public abstract class Prototype implements Cloneable {
    
    
    public abstract Prototype clone();
}

public class ConcretePrototypeA extends Prototype {
    
    
    public Prototype clone() {
    
    
        try {
    
    
            return (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
    
    
            return null;
        }
    }
}

public class Client {
    
    
    private Prototype prototype;

    public Client(public Prototype prototype) {
    
    
        this.prototype = prototype;
    }

    public Prototype createPrototype() {
    
    
        return prototype.clone();
    }
}

结构型模式

结构型模式关注对象的组合方式,包括适配器模式、桥接模式、组合模式、装饰器模式、外观模式、享元模式和代理模式。

  1. 适配器模式

适配器模式将一个类的接口转换成另一个客户端所期望的接口。它通过封装一个已有的类来实现接口的转换。

public interface Target {
    
    
    void request();
}

public class Adaptee {
    
    
    public void specificRequest() {
    
    }
}

public class Adapter implements Target {
    
    
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
    
    
        this.adaptee = adaptee;
    }

    public void request() {
    
    
        adaptee.specificRequest();
    }
}
  1. 桥接模式

桥接模式将抽象部分和实现部分分离开来,使得它们可以独立变化。它通过将实现细节委托给另一个类来完成这个过程。

public abstract class Abstraction {
    
    
    protected Implementor implementor;

    public Abstraction(Implementor implementor) {
    
    
        this.implementor = implementor;
    }

    public abstract void operation();
}

public interface Implementor {
    
    
    void operationImpl();
}

public class ConcreteImplementorA implements Implementor {
    
    
    public void operationImpl() {
    
    }
}

public class RefinedAbstraction extends Abstraction {
    
    
    public RefinedAbstraction(Implementor implementor) {
    
    
        super(implementor);
    }

    public void operation() {
    
    
        implementor.operationImpl();
    }
}
  1. 组合模式

组合模式将一组对象组织成树形结构,以表示“部分-整体”的层次结构。它允许客户端统一处理单个对象和组合对象。

public abstract class Component {
    
    
    protected String name;

    public Component(String name) {
    
    
        this.name = name;
    }

    public abstract void add(Component component);
    public abstract void remove(Component component);
    public abstract void display(int depth);
}

public class Leaf extends Component {
    
    
    public Leaf(String name) {
    
    
        super(name);
    }

    public void add(Component component) {
    
    }
    public void remove(Component component) {
    
    }

    public void display(int depth) {
    
    
        System.out.println("-".repeat(depth) + name);
    }
}

public class Composite extends Component {
    
    
    private List<Component> children = new ArrayList<>();

    public Composite(String name) {
    
    
        super(name);
    }

    public void add(Component component) {
    
    
        children.add(component);
    }

    public void remove(Component component) {
    
    
        children.remove(component);
    }

    public void display(int depth) {
    
    
        System.out.println("-".repeat(depth) + name);
        for (Component component : children) {
    
    
            component.display(depth + 1);
        }
    }
}
  1. 装饰器模式

装饰器模式可以在不改变原有对象的基础上,通过包装一个装饰器对象来扩展其功能。

public abstract class Component {
    
    
    public abstract void operation();
}

public class ConcreteComponent extends Component {
    
    
    public void operation() {
    
    }
}

public abstract class Decorator extends Component {
    
    
    protected Component component;

    public Decorator(Component component) {
    
    
        this.component = component;
    }

    public void operation() {
    
    
        component.operation();
    }
}

public class ConcreteDecoratorA extends Decorator {
    
    
    public ConcreteDecoratorA(Component component) {
    
    
        super(component);
    }

    public void operation() {
    
    
        super.operation();
        // Add extra behavior
    }
}
  1. 外观模式

外观模式提供了一个简单的接口,隐藏了一组子系统复杂的内部结构。它将客户端与子系统之间的依赖关系解耦合。

public class Subsystem1 {
    
    
    public void operation1() {
    
    }
}

public class Subsystem2 {
    
    
    public void operation2() {
    
    }
}

public class Facade {
    
    
    private Subsystem1 subsystem1;
    private Subsystem2 subsystem2;

    public Facade() {
    
    
        subsystem1 = new Subsystem1();
        subsystem2 = new Subsystem2();
    }

    public void operation() {
    
    
        subsystem1.operation1();
        subsystem2.operation2();
    }
}
  1. 享元模式

享元模式通过共享对象来减少内存中对象的数量,从而提高系统性能。它将对象分为内部状态和外部状态,内部状态可以被共享,而外部状态必须由客户端传入。

public interface Flyweight {
    
    
    void operation(String extrinsicState);
}

public class ConcreteFlyweight implements Flyweight {
    
    
    private String intrinsicState;

    public ConcreteFlyweight(String intrinsicState) {
    
    
        this.intrinsicState = intrinsicState;
    }

    public void operation(String extrinsicState) {
    
    }
}

public class FlyweightFactory {
    
    
    private Map<String, Flyweight> flyweights = new HashMap<>();

    public Flyweight getFlyweight(String key) {
    
    
        if (!flyweights.containsKey(key)) {
    
    
            flyweights.put(key, new ConcreteFlyweight(key));
        }
        return flyweights.get(key);
    }
}
  1. 代理模式

代理模式在访问对象时引入一个代理对象,以控制原始对象的访问。它可以隐藏对象的实现细节,并提供了一种安全访问对象的方式。

public interface Subject {
    
    
    void request();
}

public class RealSubject implements Subject {
    
    
    public void request() {
    
    }
}

public class Proxy implements Subject {
    
    
    private RealSubject realSubject;

    public Proxy(RealSubject realSubject) {
    
    
        this.realSubject = realSubject;
    }

    public void request() {
    
    
        // Access control and additional behavior
        realSubject.request();
        // Additional behavior
    }
}

七大设计模式原则

  1. 单一职责原则(SRP)

一个类应该只有一个引起它变化的原因。

  1. 开放封闭原则(OCP)

软件实体应该对扩展开放,对修改关闭。

  1. 里氏替换原则(LSP)

子类型必须能够完全替换掉其父类型。

  1. 接口隔离原则(ISP)

客户端不应该依赖于它不需要的接口。

  1. 依赖倒置原则(DIP)

高层模块不应该依赖于低层模块,它们应该依赖于抽象接口。抽象接口不应该依赖于具体实现,具体实现应该依赖于抽象接口。

  1. 迪米特法则(LoD)

一个对象应该对其他对象有最少的了解。

  1. 组合/聚合复用原则(CARP)

将一组对象组合成一个新的对象时,应该优先使用组合/聚合而不是继承关系来达到复用的目的。

总结

设计模式和设计原则是软件开发中非常重要的概念,它们可以帮助我们更好地理解和设计软件系统。本文介绍了常见的23种设计模式和七大设计模式原则,并提供了详细的示例代码演示。希望读者可以通过本文掌握这些知识,并在实际开发中加以运用。

猜你喜欢

转载自blog.csdn.net/weixin_43025343/article/details/131865131