门面模式(结构型)

本文介绍了门面模式的概念,通过购买商品流程的实例展示了其简化调用过程的功能。门面模式用于封装子系统的复杂性,常用于构建多层系统结构,以减少系统间的依赖并提高安全性。同时,文章对比了门面模式与代理模式和单例模式的区别,并列举了其优缺点。

定义

提供一个统一的接口,用来访问子系统的一群接口,定义了一个高级接口,让子系统更容易使用

适用场景

  1. 子系统越来越复杂,增加门面模式提供简单接口
  2. 构建多层系统结构,利用门面模式作为每层的入口,简化调用层

门面模式的实例

public class Login {
    private String userName;

    public Login(String userName) {
        this.userName = userName;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void login2page() {
        System.out.println("用户已登录:" + userName);
    }
}

public class Pay {
    private int amount;

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public Pay(int amount) {
        this.amount = amount;
    }

    public void pay2super() {
        System.out.println("支付金额:" + amount);
    }
}

public class Shipment {
    private String ShipNo;

    public String getShipNo() {
        return ShipNo;
    }

    public void setShipNo(String shipNo) {
        ShipNo = shipNo;
    }

    public Shipment(String shipNo) {
        ShipNo = shipNo;
    }

    public void ship2user() {
        System.out.println("发货成功:"+ ShipNo);
    }
}

// 门面类
public class PurchaseGoodsFacade {
    private Login login = new Login("ya");
    private Pay pay = new Pay(11);
    private Shipment shipment = new Shipment("666");

    public void purchaseGoods() {

        if(login.getUserName() != null && !login.getUserName().isEmpty()) {
            login.login2page();
            if (String.valueOf(pay.getAmount()) != null) {
                pay.pay2super();
                if (shipment.getShipNo() != null) {
                    shipment.ship2user();
                }
            }
        }
    }

    public static void main(String[] args) {
        PurchaseGoodsFacade facade = new PurchaseGoodsFacade();
        facade.purchaseGoods();
    }
}

应用

  1. jdbcUtil - supportsBatchUpdates
  2. mybatis - configuration- newMeta
  3. tomcat

与其他设计模式区别

  1. 代理模式
    1. 特殊的静态代理
    2. 门面模式重点在于封装
    3. 静态代理在于增强
  2. 单例模式
    1. 一般门面模式会设计成单例模式

优点

  1. 简化调用过程
  2. 减少系统依赖,松散耦合
  3. 更好的划分层次,提高安全性
  4. 最少知道原则

缺点

  1. 子系统扩展子系统行为时可能带来危险
  2. 不符合开闭原则
  3. 某些情况违背单一职责原则
<think>好的,用户想了解结构型设计模式的示例代码和解释。首先,我需要回顾结构型设计模式的种类,包括适配器、桥接、组合、装饰器、外观、享元和代理模式。接下来,用户可能需要每个模式的简要说明和代码示例。 要确保代码示例简洁易懂,最好用常见的场景,比如适配器模式可以用不同接口的兼容问题。装饰器模式适合动态添加功能的情况,比如咖啡加调料。外观模式可以展示如何简化复杂子系统调用。 需要注意用户提到的是结构型模式,所以不要混淆创建型或行为型模式。引用中提到的桥接、门面(外观)、代理模式都有相关例子,可以优先选择这些。另外,代码示例需要用Python,因为用户之前的示例也是Python。 还要检查引用内容,引用[3]提到了桥接模式,引用[4]提到了外观和代理模式,这些可以作为参考。需要确保每个模式都附有解释和代码,同时结构清晰,分点说明。最后,生成相关问题,帮助用户进一步学习。</think>### 结构型设计模式示例与代码解释 以下是6种典型结构型设计模式的Python实现示例及核心原理说明: --- #### 1. 适配器模式(Adapter Pattern) **作用**:使不兼容接口的类能够协同工作 **示例**:将旧版充电器的USB-A接口适配为Type-C ```python class USBACharger: def usb_a_charge(self): return "USB-A充电中..." class TypeCAdapter: def __init__(self, charger): self.charger = charger def type_c_charge(self): return f"适配器转换:{self.charger.usb_a_charge()}" adapter = TypeCAdapter(USBACharger()) print(adapter.type_c_charge()) # 输出:适配器转换:USB-A充电中... ``` --- #### 2. 桥接模式(Bridge Pattern) **作用**:分离抽象与实现,使两者独立变化[^3] **示例**:不同形状使用不同渲染引擎 ```python class RenderEngine: def render_circle(self, radius): pass class OpenGL(RenderEngine): def render_circle(self, radius): return f"OpenGL绘制圆形(半径{radius})" class Shape: def __init__(self, renderer): self.renderer = renderer class Circle(Shape): def draw(self, radius): print(self.renderer.render_circle(radius)) Circle(OpenGL()).draw(5) # 输出:OpenGL绘制圆形(半径5) ``` --- #### 3. 装饰器模式(Decorator Pattern) **作用**:动态添加对象功能 **示例**:为咖啡添加配料 ```python class Coffee: def cost(self): return 20 class MilkDecorator: def __init__(self, coffee): self.coffee = coffee def cost(self): return self.coffee.cost() + 5 base_coffee = Coffee() print(f"基础咖啡价格:{base_coffee.cost()}元") # 输出:20 print(f"加奶咖啡价格:{MilkDecorator(base_coffee).cost()}元") # 输出:25 ``` --- #### 4. 外观模式(Facade Pattern) **作用**:简化复杂子系统调用[^4] **示例**:智能家居统一控制 ```python class LightSystem: def set_light(self, level): print(f"灯光设置为{level}%") class TemperatureSystem: def set_temp(self, degree): print(f"温度设置为{degree}℃") class SmartHomeFacade: def __init__(self): self.light = LightSystem() self.temp = TemperatureSystem() def evening_mode(self): self.light.set_light(30) self.temp.set_temp(25) SmartHomeFacade().evening_mode() # 同时控制灯光和温度 ``` --- #### 5. 代理模式(Proxy Pattern) **作用**:控制对象访问,添加中间层[^4] **示例**:图片懒加载 ```python class HighResImage: def display(self): print("显示高清图片(耗时2秒)") class ImageProxy: def __init__(self): self._image = None def display(self): if not self._image: self._image = HighResImage() self._image.display() proxy = ImageProxy() proxy.display() # 首次加载会延迟 proxy.display() # 直接使用缓存 ``` --- #### 6. 组合模式(Composite Pattern) **作用**:树形结构处理统一接口 **示例**:文件系统管理 ```python class FileComponent: def show(self, indent=0): pass class File(FileComponent): def show(self, indent=0): print(" "*indent + "📄 文件") class Folder(FileComponent): def __init__(self): self.children = [] def add(self, component): self.children.append(component) def show(self, indent=0): print(" "*indent + "📁 文件夹") for child in self.children: child.show(indent+1) root = Folder() root.add(File()) sub_folder = Folder() sub_folder.add(File()) root.add(sub_folder) root.show() ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值