答答问 > 投稿 > 正文
【解锁面向对象编程奥秘】揭秘十大经典设计模式

作者:用户GDPZ 更新时间:2025-06-09 04:22:45 阅读时间: 2分钟

在软件开发领域,设计模式是经过时间验证的解决方案,它们可以帮助开发者解决在软件设计过程中经常遇到的问题。面向对象编程(OOP)中的设计模式分为三大类:创建型模式、结构型模式和行为型模式。以下是十大经典设计模式及其详细介绍:

1. 单例模式(Singleton Pattern)

用途:确保一个类只有一个实例,并提供一个全局访问点。

实现:在类中创建一个静态实例,并提供一个公共的静态方法返回该实例。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

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

用途:定义一个用于创建对象的接口,让子类决定实例化哪一个类。

实现:定义一个接口用于创建对象,然后让子类决定实现哪个类。

public interface Creator {
    <T> T create(Class<T> c);
}

public class ConcreteCreator implements Creator {
    public <T> T create(Class<T> c) {
        return c.cast(new ConcreteProduct());
    }
}

3. 建造者模式(Builder Pattern)

用途:将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

实现:定义一个建造者接口和多个实现类,用于构建复杂对象。

public interface Builder {
    void partA();
    void partB();
    Product getResult();
}

public class ConcreteBuilder implements Builder {
    private Product product = new Product();

    public void partA() {
        product.setPartA("partA");
    }

    public void partB() {
        product.setPartB("partB");
    }

    public Product getResult() {
        return product;
    }
}

4. 适配器模式(Adapter Pattern)

用途:将一个类的接口转换成客户端期望的接口。

实现:创建一个适配器类,它实现了客户端期望的接口,并将客户端的请求转发给适配的对象。

public class Adapter {
    private Adaptee adaptee;

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

    public void request() {
        adaptee SpecificRequest();
    }
}

5. 装饰器模式(Decorator Pattern)

用途:动态地给一个对象添加额外的功能。

实现:创建一个装饰器类,它实现了被装饰类接口,并在内部持有被装饰对象的引用。

public class Decorator implements Component {
    private Component component;

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

    public void operation() {
        component.operation();
        // 添加额外功能
    }
}

6. 组合模式(Composite Pattern)

用途:将对象组合成树形结构,以表示部分-整体层次结构。

实现:定义一个组件接口和叶节点类,以及一个容器类,它包含组件列表。

public interface Component {
    void operation();
}

public class Leaf implements Component {
    public void operation() {
        // 具体操作
    }
}

public class Composite implements Component {
    private List<Component> components = new ArrayList<>();

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

    public void operation() {
        for (Component component : components) {
            component.operation();
        }
    }
}

7. 代理模式(Proxy Pattern)

用途:为其他对象提供一种代理以控制对这个对象的访问。

实现:创建一个代理类,它实现了与被代理对象相同的接口,并在内部持有被代理对象的引用。

public class Proxy implements Subject {
    private RealSubject realSubject;

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

    public void request() {
        realSubject.request();
    }
}

8. 观察者模式(Observer Pattern)

用途:定义对象之间的一对多依赖关系,当一个对象状态改变时,其所有依赖对象都会收到通知。

实现:创建一个观察者接口和多个观察者类,以及一个主题类,它持有一个观察者列表。

public interface Observer {
    void update(Subject subject);
}

public class ConcreteObserver implements Observer {
    public void update(Subject subject) {
        // 更新逻辑
    }
}

public class Subject {
    private List<Observer> observers = new ArrayList<>();

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(this);
        }
    }
}

9. 策略模式(Strategy Pattern)

用途:定义一系列的算法,将每个算法封装起来,并使它们可以互相替换。

实现:创建一个策略接口和多个实现类,以及一个上下文类,它使用策略接口。

public interface Strategy {
    void execute();
}

public class ConcreteStrategyA implements Strategy {
    public void execute() {
        // 算法A
    }
}

public class ConcreteStrategyB implements Strategy {
    public void execute() {
        // 算法B
    }
}

public class Context {
    private Strategy strategy;

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public void executeStrategy() {
        strategy.execute();
    }
}

10. 职责链模式(Chain of Responsibility Pattern)

用途:避免硬编码的接收者,允许请求沿着处理者链传递,直到被处理。

实现:创建一个处理者接口和多个处理者类,它们实现处理者接口。

public interface Handler {
    void handle(Request request);
}

public class ConcreteHandlerA implements Handler {
    private Handler nextHandler;

    public void setNextHandler(Handler nextHandler) {
        this.nextHandler = nextHandler;
    }

    public void handle(Request request) {
        // 处理请求
        if (nextHandler != null) {
            nextHandler.handle(request);
        }
    }
}

通过学习这些经典设计模式,开发者可以更好地理解和应用面向对象编程原则,提高代码的可读性、可维护性和可扩展性。

大家都在看
发布时间:2024-11-11 12:01
1、朝暮与岁月并往,愿我们一同行至天光。 2、新年愿望是:愿贪吃不胖,愿懒惰不丑,愿深情不被辜负。 3、看新一轮的光怪陆离,江湖海底,和你一起。 4、希望开心与好运奔向我,我们撞个满怀。 5、新年到心情好,新年到财运到,新。
发布时间:2024-11-02 08:33
如果检测结果为血糖14的话,已经明显高于正常的6.16了,所以这属于标准的高血糖,如果长期血糖这么高的话,要警惕出现了糖尿病,患者最好到医院进行进一步的检查。
发布时间:2024-12-12 03:17
北京地铁16号线(以抄下袭简称“16号线”),是北京地铁的一条建设中的南北向骨干线,途经丰台、西城、海淀3个行政区,由京港地铁运营。线路南起于丰台区宛平城站,经过北京丽泽金融商务区、西城三里河、国家图书馆、苏州街、永丰科技园区、海淀山后地。