Java设计模式-桥接模式

一、概述

桥接模式是指:将实现与抽象放在两个不同的类层次中,使两个层次可以独立改变,是一种结构型设计模式

二、角色

抽象化(Abstraction):抽象化给出的定义,并保存一个对实现化对象的引用,Abstraction充当桥接类

修正抽象化(Refined Abstraction):扩展抽象化角色,改变和修正父类对抽象化的定义

实现化(Implementor):这个角色给出实现化角色的接口,但不给出具体的实现,必须指出的是,这个接口不一定和抽象化角色的接口定义相同,实际上,者两个接口可以非常不一样。实现化角色应当只给出底层操作,而抽象化角色应当只给出基于底层操作的更高一层的操作

具体实现化(Concrete Implementor):这个角色给出实现化角色接口的具体实现

三、桥接模式

1.抽象化

/**
 * 抽象化角色类,它声明了一个方法operation(),并给出了它的实现,这个实现是通过
 * 向实现化对象的委派(调用operationImpl()方法)实现的
 */
public abstract class Abstraction {
    protected Implementor impl;

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

    public void operation() {
        impl.operationImpl();
    }
}

2.修正抽象化

public class RefinedAbstraction extends Abstraction {

    public RefinedAbstraction(Implementor impl) {
        super(impl);
    }

    // 其他的操作方法
    public void otherOperation() {

    }
}

3.实现化

public abstract class Implementor {
    /**
     * 示例方法,实现抽象部分需要的某些具体功能
     */
    public abstract void operationImpl();
}

4.具体实现化

public class ConcreteImplementorA extends Implementor {
    @Override
    public void operationImpl() {
        // 具体操作
    }
}
public class ConcreteImplementorB extends Implementor {
    @Override
    public void operationImpl() {
        // 具体操作
    }
}

四、使用

1.品牌类型

// 品牌
public interface Brand {
    void info();
}

class Lenovo implements Brand {

    @Override
    public void info() {
        System.out.print("Lenovo ");
    }
}

class Apple implements Brand {

    @Override
    public void info() {
        System.out.print("Apple ");
    }
}

2.电脑类型

// 抽象的电脑类型
public abstract class Computer {

    protected Brand brand;

    public Computer(Brand brand) {
        this.brand = brand;
    }

    public void info() {
        brand.info();
    }
}

class Desktop extends Computer {

    public Desktop(Brand brand) {
        super(brand);
    }

    @Override
    public void info() {
        super.info();
        System.out.print("Desktop ");
    }
}

class Laptop extends Computer {

    public Laptop(Brand brand) {
        super(brand);
    }

    @Override
    public void info() {
        super.info();
        System.out.print("Laptop ");
    }
}

3.测试

@Test
public void testBridge() {
    Computer c1 = new Desktop(new Apple());
    c1.info();
    Computer c2 = new Laptop(new Lenovo());
    c2.info();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值