Bridge桥接模式

Bridge pattern

The bridge pattern is a design pattern used in software engineering that is meant to “decouple an abstraction from its implementation so that the two can vary independently”, introduced by the Gang of Four.[1] The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
When a class varies often, the features of object-oriented programming become very useful because changes to a program’s code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class and what it does vary often. The class itself can be thought of as the abstraction and what the class can do as the implementation. The bridge pattern can also be thought of as two layers of abstraction. —Wikipedia

Structure

在这里插入图片描述

Example

小哥哥送小姐姐礼物

礼物分为抽象的礼物和具体的礼物

抽象的礼物:Gift_、WarmGift_、WildGift_

具体的礼物:GiftImpl_、Book_、Flower_

抽象的礼物和具体的礼物分为 2 个继承体系,抽象礼物初始化时需传入具体礼物的实现类

public class Main {
    public static void main(String[] args) {
        new GG_().chase(new MM_());
    }
}

abstract class Gift_ {
    GiftImpl_ impl;
}

class WarmGift_ extends Gift_ {
    public WarmGift_(GiftImpl_ impl) {
        this.impl = impl;
    }
}

class WildGift_ extends Gift_ {
    public WildGift_(GiftImpl_ impl) {
        this.impl = impl;
    }
}

class GiftImpl_ {
}

class Book_ extends GiftImpl_ {
}

class Flower_ extends GiftImpl_ {
}

class GG_ {
    public void chase(MM_ mm) {
        Gift_ g = new WarmGift_(new Flower_());
        give(mm, g);
    }

    public void give(MM_ mm, Gift_ g) {
        System.out.println(g + "gived!");
    }

}

class MM_ {
    String name;
}

在这里插入图片描述

Summary

  • 分离抽象与具体
  • 用聚合方式(桥)连接抽象与具体
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值