设计模式-结构型模式-桥接模式

02-29 阅读 0评论

桥接模式(Bridge Pattern):将抽象部分与其实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。桥接模式用一种巧妙的方式处理多层继承存在的问题。桥接模式采用抽象关联取代了传统的多层继承,将类之间的静态继承关系转换为动态的对象组合关系,使得系统更加灵活,并易于扩展,同时有效控制了系统中类的个数。

设计模式-结构型模式-桥接模式,设计模式-结构型模式-桥接模式,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,接口,关系,第1张
(图片来源网络,侵删)

合成/聚合复用原则(CARP),尽量使用合成/聚合,尽量不要使用类继承。[J&DP]

设计模式-结构型模式-桥接模式 

 

//首先,我们定义一个接口Implementor,它表示实现部分的接口
public interface Implementor {
    void operationImpl();
}
//然后,我们创建两种实现这个接口的具体类:
public class ConcreteImplementorA implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("ConcreteImplementorA operationImpl()");
    }
}
public class ConcreteImplementorB implements Implementor {
    @Override
    public void operationImpl() {
        System.out.println("ConcreteImplementorB operationImpl()");
    }
}
//接下来,我们定义一个抽象类Abstraction,它包含一个对Implementor的引用:
public abstract class Abstraction {
    protected Implementor implementor;
    public Abstraction(Implementor implementor) {
        this.implementor = implementor;
    }
    public void operation() {
        implementor.operationImpl();
    }
}
//现在,我们创建两个继承自Abstraction的具体类,每个都接受一个特定的Implementor类型:
public class RefinedAbstractionA extends Abstraction {
    public RefinedAbstractionA(Implementor implementor) {
        super(implementor);
    }
}
public class RefinedAbstractionB extends Abstraction {
    public RefinedAbstractionB(Implementor implementor) {
        super(implementor);
    }
}
//最后,在客户端代码中,我们可以根据需要组合抽象部分和实现部分:
public class Client {
    public static void main(String[] args) {
        Implementor implementorA = new ConcreteImplementorA();
        Implementor implementorB = new ConcreteImplementorB();
        Abstraction abstractionA1 = new RefinedAbstractionA(implementorA);
        Abstraction abstractionA2 = new RefinedAbstractionA(implementorB);
        Abstraction abstractionB1 = new RefinedAbstractionB(implementorA);
        Abstraction abstractionB2 = new RefinedAbstractionB(implementorB);
        // 使用不同的组合调用operation
        abstractionA1.operation();
        abstractionA2.operation();
        abstractionB1.operation();
        abstractionB2.operation();
    }
}
设计模式-结构型模式-桥接模式,设计模式-结构型模式-桥接模式,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,接口,关系,第3张
(图片来源网络,侵删)
设计模式-结构型模式-桥接模式,设计模式-结构型模式-桥接模式,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,使用,接口,关系,第4张
(图片来源网络,侵删)

免责声明
本网站所收集的部分公开资料来源于AI生成和互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复: 表情:
评论列表 (暂无评论,人围观)

还没有评论,来说两句吧...

目录[+]