软件编程
位置:首页>> 软件编程>> java编程>> Java设计模式之桥接模式的实现

Java设计模式之桥接模式的实现

作者:RYGAR  发布时间:2021-10-18 20:29:04 

标签:Java,桥接模式

桥接模式

桥接模式是将抽象部分与它的实现部分分离,使他们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。

Java设计模式之桥接模式的实现

上图一个类被三个类继承,使我们的程序扩展性,可维护性低,违反了单一职责原则。

Java设计模式之桥接模式的实现

具体代码实现如下:

1.创建品牌接口


package com.jialidun.gof.birdge;

//品牌
public interface Brand {

void info();
}

2.创建计算机的抽象类


package com.jialidun.gof.birdge;

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

//组合,品牌 桥
   protected Brand brand;

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

public void info(){
       brand.info();//自带品牌

}
}

3.苹果品牌


package com.jialidun.gof.birdge;

//苹果品牌
public class Apple implements Brand{
   @Override
   public void info() {
       System.out.print("苹果"+"\n");
   }
}

4.联想品牌


package com.jialidun.gof.birdge;

//联想品牌
public class Lenovo implements Brand{
   @Override
   public void info() {
       System.out.print("联想"+"\n");
   }
}

5.台式机


package com.jialidun.gof.birdge;

public class Desktop extends Computer{
   public Desktop(Brand brand) {
       super(brand);
       System.out.print("台式机");
   }
}

6.笔记本


package com.jialidun.gof.birdge;

public class laptop extends Computer{
   public laptop(Brand brand) {
       super(brand);
       System.out.print("笔记本");
   }
}

7.测试


package com.jialidun.gof.birdge;

public class Test {
   public static void main(String[] args) {
       //苹果笔记本
       Computer computer = new laptop(new Apple());
       computer.info();

//联想台式机
       Desktop desktop = new Desktop(new Lenovo());
       desktop.info();

}
}

Java设计模式之桥接模式的实现

好处分析:

1.桥接模式偶尔类似于多继承方案,但是多继承方案违背了类的单一职责原则, 复用性比较差,类的个数也非常多,桥接模式是比多继承方案更好的解决方法。极大的减少了子类的个数,从而降低管理和维护的成本

2.桥接模式提高了系统的可扩充性,在两个变化维度中任意扩展一个维度,都不需要修改原有系统。符合开闭原则,就像一座桥,可以把两个变化的维度连接起来

劣势分析

1.桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。

2.桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性。

来源:https://blog.csdn.net/m0_51067047/article/details/117571707

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com