Java常用设计模式

发布于:2024-07-02 ⋅ 阅读:(17) ⋅ 点赞:(0)

引言

设计模式是软件工程中的一种模板,用于解决在软件设计过程中遇到的常见问题。设计模式不是代码,而是解决特定问题的策略。Java作为一种面向对象的编程语言,提供了丰富的特性来实现各种设计模式。

创建型模式

创建型模式主要关注对象的创建过程,隐藏创建逻辑,实例化对象的代码不会依赖于具体类。Java中常见的创建型模式有:

1. 单例模式(Singleton)

单例模式确保一个类只有一个实例,并提供一个全局访问点。

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

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

工厂方法模式定义了一个创建对象的接口,让子类决定实例化哪一个类。

interface Product { void use(); }
class ConcreteProduct implements Product { public void use() { ... } }
abstract class Creator { abstract Product factoryMethod(); }
class ConcreteCreator extends Creator {
    public Product factoryMethod() { return new ConcreteProduct(); }
}

3. 抽象工厂模式(Abstract Factory)

抽象工厂模式创建相关或依赖对象的家族,而不需明确指定具体类。

interface ProductA { void useA(); }
interface ProductB { void useB(); }
interface AbstractFactory { ProductA createProductA(); ProductB createProductB(); }
class ConcreteFactory implements AbstractFactory {
    public ProductA createProductA() { return new ProductAImpl(); }
    public ProductB createProductB() { return new ProductBImpl(); }
}

4. 建造者模式(Builder)

建造者模式用于创建一个复杂对象,同时允许用户只通过指定复杂对象的类型和内容就能构建它们。

class Product {
    public void setPart(String part) { ... }
    public static class Builder {
        private Product product = new Product();
        public Builder setPart(String part) {
            product.setPart(part);
            return this;
        }
        public Product build() { return product; }
    }
}

5. 原型模式(Prototype)

原型模式通过拷贝现有的实例创建新的实例,而不是通过新建。

class Prototype implements Cloneable {
    public void use() { ... }
    public Prototype clone() { ... }
}

结构型模式

结构型模式主要关注对象的组合,继承和成员管理,它们定义了如何将对象组合成更大的结构。

1. 适配器模式(Adapter)

适配器模式将一个类的接口转换成客户期望的另一个接口。

interface Target { void request(); }
class Adaptee { public void specificRequest() { ... } }
class Adapter implements Target {
    private Adaptee adaptee;
    public Adapter(Adaptee adaptee) { this.adaptee = adaptee; }
    public void request() { adaptee.specificRequest(); }
}

2. 装饰器模式(Decorator)

装饰器模式动态地给一个对象添加额外的职责。

interface Component { void operate(); }
abstract class Decorator implements Component {
    protected Component component;
    public Decorator(Component component) { this.component = component; }
    public void operate() { component.operate(); }
}
class ConcreteComponent implements Component { public void operate() { ... } }
class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) { super(component); }
    public void operate() {
        super.operate();
        // 添加额外职责
    }
}

3. 代理模式(Proxy)

代理模式为另一个对象提供一个代替或占位符,以控制对它的访问。

interface Subject { void request(); }
class RealSubject implements Subject { public void request() { ... } }
class Proxy implements Subject {
    private RealSubject realSubject;
    public Proxy() { this.realSubject = new RealSubject(); }
    public void request() {
        // 代理职责
        realSubject.request();
    }
}

4. 外观模式(Facade)

外观模式提供了一个统一的高层接口,用来访问子系统中的一群接口。

class SubSystemOne { public void operation1() { ... } }
class SubSystemTwo { public void operation2() { ... } }
class Facade {
    private SubSystemOne one;
    private SubSystemTwo two;
    public Facade() { one = new SubSystemOne(); two = new SubSystemTwo(); }
    public void operation() {
        one.operation1();
        two.operation2();
    }
}

5. 桥接模式(Bridge)

桥接模式将抽象部分与它的实现部分分离,使它们可以独立地变化。

abstract class Abstraction {
    protected Implementor implementor;
    public Abstraction(Implementor implementor) {
        this.implementor = implementor;
    }
    public void operation() {
        implementor.operationImplementor();
    }
}
interface Implementor {
    void operationImplementor();
}
class ConcreteImplementorA implements Implementor {
    public void operationImplementor() { ... }
}

行为型模式

行为型模式主要关注对象间的通信,它们将对象的行为和算法封装起来,独立于客户端。

1. 策略模式(Strategy)

策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以互换。

interface Strategy { void algorithm(); }
class ConcreteStrategyA implements Strategy { public void algorithm() { ... } }
class Context {
    private Strategy strategy;
    public Context(Strategy strategy) { this.strategy = strategy; }
    public void executeStrategy() { strategy.algorithm(); }
}

2. 模板方法模式(Template Method)

模板方法模式定义了一个算法的骨架,将一些步骤的执行延迟到子类。

abstract class AbstractClass {
    public void templateMethod() {
        baseOperation1();
        baseOperation2();
        operation();
    }
    protected abstract void operation();
    protected void baseOperation1() { ... }
    protected void baseOperation2() { ... }
}
class ConcreteClass extends AbstractClass {
    protected void operation() { ... }
}

3. 观察者模式(Observer)

观察者模式定义了对象间的一种一对多的依赖关系,当一个对象改变状态时,所有依赖于它的对象都得到通知并自动更新。

interface Observer { void update(); }
interface Subject {
    void attach(Observer o);
    void detach(Observer o);
    void notifyObservers();
}
class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();
    public void attach(Observer o) { observers.add(o); }
    public void detach(Observer o) { observers.remove(o); }
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update();
        }
    }
}

4. 迭代器模式(Iterator)

迭代器模式提供一种顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。

interface Iterator {
    boolean hasNext();
    Object next();
}
interface Aggregate {
    Iterator createIterator();
}
class ConcreteIterator implements Iterator {
    private List<Object> items;
    private int position = 0;
    public ConcreteIterator(List<Object> items) { this.items = items; }
    public boolean hasNext() { return position < items.size(); }
    public Object next() { return items.get(position++); }
}

5. 责任链模式(Chain of Responsibility)

责任链模式使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。

interface Handler {
    void handleRequest(Request request);
}
class ConcreteHandlerA extends Handler {
    private Handler next;
    public void setNext(Handler next) { this.next = next; }
    public void handleRequest(Request request) {
        if (next != null) {
            next.handleRequest(request);
        }
    }
}

结语

设计模式是软件开发过程中的宝贵财富,它们提供了解决特定问题的通用方法。掌握设计模式不仅能够帮助开发者写出更加优雅、灵活和可维护的代码,而且能够促进团队之间的沟通和代码的共享。Java作为一门广泛应用的编程语言,其对设计模式的支持非常全面,学习和应用Java设计模式对于提升编程技能至关重要。