<设计模式11>桥接模式

来源:互联网 发布:淘宝是网站吗 编辑:程序博客网 时间:2024/06/06 08:45

桥接模式是用于“把抽象和实现分开,这样它们就能独立变化”。 桥接模式使用了封装、聚合,可以用继承将不同的功能拆分为不同的类。

“桥接”的作用就是连接“抽象”与“实现”部分,如果一个系统需要在构建的抽象化角色和具体角色之前增加更多的灵活性,而不是静态的直接继承实现,则可以考虑桥接模式。

我们以球鞋为例,生活中有很多的球鞋,白色、黑色;篮球鞋、足球鞋;阿迪达斯、nike,等等,他们不同,但是都却有着相似的地方。

下面通过桥接模式来实现这个过程。

shoe的接口:

public interface IShoes {void makeShoes();}

鞋子有Adidas和Nike两种:

public class NikeShoesImpl implements IShoes {@Overridepublic void makeShoes() {System.out.println("制造Nike的鞋子");}}
public class AdidasShoesImpl implements IShoes {@Overridepublic void makeShoes() {System.out.println("制造Adidas的鞋子");}}

因为鞋子有着不同的类型,我们需要灵活的创建,不能定死,就需要新建一个Brige

public abstract class Bridge {private IShoes shoes;public Bridge(IShoes shoes){this.shoes = shoes;}//对鞋子进行生产public void bridgeOperate(){shoes.makeShoes();}}

Bridge也有这多种,分别生产白色的、黑色的鞋子,不同bridge生产不同鞋子:

public class BlackBridgeImpl extends Bridge {public BlackBridgeImpl(IShoes shoes) {super(shoes);}    public void otherOperation() {    System.out.println("加工为黑色球鞋");    }}
public class WhiteBridgeImpl extends Bridge {public WhiteBridgeImpl(IShoes shoes) {super(shoes);}    public void otherOperation() {    System.out.println("加工为白色球鞋");    }}

测试代码:

public class BridgeTest {public static void main(String[] args) {IShoes nikeShoes = new NikeShoesImpl();IShoes adidasShoes = new AdidasShoesImpl();BlackBridgeImpl blackImpl = new BlackBridgeImpl(adidasShoes);blackImpl.bridgeOperate();blackImpl.otherOperation();}}
当我们要生产nike鞋的时候就传入nike,而Bridge只负责确定黑色还是白色,这样通过传入的shoe类型,动态生产了不同公司的鞋子。
结果:

制造Adidas的鞋子

加工为黑色球鞋

上面就是一个桥接模式的基本使用雏形。只需要传入一些不同的参数,不需要更改多少就可以得到不同的结果。



1 0
原创粉丝点击