Java设计模式 七 结构型模式 (Structural Patterns)

结构型模式 (Structural Patterns) 是一种设计模式,主要关注如何通过合理组织类和对象来形成更大的结构。它解决了类与对象之间的组合或继承关系,旨在实现更高的灵活性和可扩展性,同时减少系统复杂度。

结构型模式有以下几种:


1. 适配器模式 (Adapter Pattern)

定义:
将一个类的接口转换成客户端期望的另一个接口,使原本不兼容的接口能够协同工作。

应用场景:

  • 需要复用现有类,但它的接口不符合当前需求时。
  • 不修改原有类的情况下,让新旧代码协同工作。

示例代码:

// 目标接口
public interface Target {
    void request();
}

// 适配者类(已有接口)
public class Adaptee {
    public void specificRequest() {
        System.out.println("Specific request from Adaptee.");
    }
}

// 适配器类
public class Adapter implements Target {
    private Adaptee adaptee;

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

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

// 客户端
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request();
    }
}

2. 桥接模式 (Bridge Pattern)

定义:
将抽象部分与其实现部分分离,使它们可以独立变化。

应用场景:

  • 避免多层继承导致的类爆炸问题。
  • 需要将抽象和实现解耦,使它们独立变化。

示例代码:

// 实现部分接口
public interface Implementor {
    void operationImpl();
}

// 具体实现
public class ConcreteImplementorA implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("ConcreteImplementorA operation.");
    }
}

// 抽象部分
public abstract class Abstraction {
    protected Implementor implementor;

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

    public abstract void operation();
}

// 扩展抽象
public class RefinedAbstraction extends Abstraction {
    public RefinedAbstraction(Implementor implementor) {
        super(implementor);
    }

    @Override
    public void operation() {
        implementor.operationImpl();
    }
}

// 客户端
public class Client {
    public static void main(String[] args) {
        Implementor implementor = new ConcreteImplementorA();
        Abstraction abstraction = new RefinedAbstraction(implementor);
        abstraction.operation();
    }
}

3. 装饰器模式 (Decorator Pattern)

定义:
动态地为对象添加新的职责,而不改变其结构。

应用场景:

  • 动态扩展对象的功能。
  • 替代继承以增强功能。

示例代码:

// 抽象组件
public interface Component {
    void operation();
}

// 具体组件
public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("ConcreteComponent operation.");
    }
}

// 抽象装饰器
public abstract class Decorator implements Component {
    protected Component component;

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

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

// 具体装饰器
public class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        System.out.println("ConcreteDecoratorA additional operation.");
    }
}

// 客户端
public class Client {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        Component decorator = new ConcreteDecoratorA(component);
        decorator.operation();
    }
}

4. 外观模式 (Facade Pattern)

定义:
为子系统中的一组接口提供一个统一的高层接口,使子系统更易于使用。

应用场景:

  • 简化复杂子系统的使用。
  • 需要为子系统提供单一入口点。

示例代码:

// 子系统A
public class SubsystemA {
    public void operationA() {
        System.out.println("SubsystemA operation.");
    }
}

// 子系统B
public class SubsystemB {
    public void operationB() {
        System.out.println("SubsystemB operation.");
    }
}

// 外观类
public class Facade {
    private SubsystemA subsystemA;
    private SubsystemB subsystemB;

    public Facade() {
        this.subsystemA = new SubsystemA();
        this.subsystemB = new SubsystemB();
    }

    public void operation() {
        subsystemA.operationA();
        subsystemB.operationB();
    }
}

// 客户端
public class Client {
    public static void main(String[] args) {
        Facade facade = new Facade();
        facade.operation();
    }
}

5. 享元模式 (Flyweight Pattern)

定义:
通过共享技术有效地支持大量细粒度对象。

应用场景:

  • 系统中存在大量相似对象,且这些对象可以共享状态。

示例代码:

import java.util.HashMap;
import java.util.Map;

// 抽象享元
public interface Flyweight {
    void operation(String extrinsicState);
}

// 具体享元
public class ConcreteFlyweight implements Flyweight {
    private String intrinsicState;

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

    @Override
    public void operation(String extrinsicState) {
        System.out.println("IntrinsicState: " + intrinsicState + ", ExtrinsicState: " + extrinsicState);
    }
}

// 享元工厂
public class FlyweightFactory {
    private Map<String, Flyweight> pool = new HashMap<>();

    public Flyweight getFlyweight(String key) {
        if (!pool.containsKey(key)) {
            pool.put(key, new ConcreteFlyweight(key));
        }
        return pool.get(key);
    }
}

// 客户端
public class Client {
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight flyweight1 = factory.getFlyweight("A");
        Flyweight flyweight2 = factory.getFlyweight("B");
        Flyweight flyweight3 = factory.getFlyweight("A");

        flyweight1.operation("X");
        flyweight2.operation("Y");
        flyweight3.operation("Z");
    }
}

6. 代理模式 (Proxy Pattern)

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

应用场景:

  • 控制访问权限。
  • 延迟加载。
  • 提供远程代理。

示例代码:

// 抽象主题
public interface Subject {
    void request();
}

// 真实主题
public class RealSubject implements Subject {
    @Override
    public void request() {
        System.out.println("RealSubject request.");
    }
}

// 代理
public class Proxy implements Subject {
    private RealSubject realSubject;

    @Override
    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        System.out.println("Proxy: Delegating request.");
        realSubject.request();
    }
}

// 客户端
public class Client {
    public static void main(String[] args) {
        Subject proxy = new Proxy();
        proxy.request();
    }
}

总结

模式作用示例
适配器模式使接口不兼容的类可以协同工作InputStreamReader
桥接模式分离抽象和实现,使两者独立变化图形库(形状与颜色)
装饰器模式动态扩展对象的功能BufferedReader
外观模式提供子系统的简化接口数据库连接管理
享元模式共享对象以减少内存使用字符对象池
代理模式控制对象访问或增加额外功能动态代理

这些模式通过不同的方式优化代码结构,使系统更加灵活、可维护。根据实际需求选择合适的模式可以有效提升代码质量。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十方来财

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值