Case Study: Design Patterns and structural characteristics of the code (bridge mode)

basic introduction:

1) bridge mode (Bridge mode) refers to: be implemented in two different abstract class hierarchy, so that two levels can be varied independently.

2) a structural design pattern.

3) Bridge mode based on the principle of minimal design classes by using encapsulation, inheritance and aggregation behavior to allow different classes to assume different responsibilities. Its main feature is the abstraction (Abstraction) and behavior to achieve (Implementation) separated, so you can maintain the independence of each part and deal with their extensions.

Mode structure:

 AbstractBike: abstract class

 MountatinBike / RoadBike: Extended abstract class

 InterfaceBrand: the interface implementation class

 MeridaBrand / GiantBrand: implementation class

 

 

 

 

 

case analysis:

A typical implementation class interface code:
 public  interface InterfaceBrand {
    public  void showBrand ();
}
Typical abstract class code:
public abstract class AbstractBike {
   InterfaceBrand brand;//自行车的品牌
   String color;//自行车的颜色
   public AbstractBike(InterfaceBrand brand, String color) {
      this.brand = brand;
      this.color = color;
   }
   public abstract void print();
}
典型的扩充抽象类代码:
public class MountatinBike extends AbstractBike {
   public MountatinBike(InterfaceBrand brand, String color) {
      super( brand, color);
   }
   public void print(){
      System.out.println("属性:山地车");
      System.out.println("颜色:"+color);
      brand.showBrand();
      System.out.println("---------------");
   }
}
典型的接口的实现的代码:
public class GiantBrand implements InterfaceBrand {
   @Override
   public void showBrand() {
      
      System.out.println("-品牌:捷安特");
   }
}

 

模块抽象封装的方法:

在该场景中,如果要增加品牌的种类,只需要增加接口的实现即可,可扩展性强;如果增加车子种类(比如说旅行车、城市车),只需要增加抽象类的实现,实现了抽象和实现部分的分离。

引入该设计模式后对系统架构和代码结构带来了的好处:

实现了抽象和实现部分的分离,从而极大的提供了系统的灵活性,让抽象部分和实现部分独立开来,这有助于系统进行分层设计,从而产生更好的结构化系统。

对于系统的高层部分,只需要知道抽象部分和实现部分的接口就可以了,其它的部分由具体业务来完成。

桥接模式替代多层继承方案,可以减少子类的个数,降低系统的管理和维护成本。

其中用到的多态机制:

多态三个必要条件:继承、方法重写、父类引用指向子类对象。

本案例中RoadBike、MountatinBike继承父类(抽象类)AbstractBike,对父类方法print()进行重写。代码如下:

InterfaceBrand brand1=new GiantBrand();

InterfaceBrand brand2=new GiantBrand();

AbstractBike bike1=new MountatinBike(brand1,"黑色");

AbstractBike bike2=new RoadBike(brand1,"红色");

bike1.print();

bike2.print();

 

分析各个模块的内聚度和模块之间的耦合度:

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

将抽象化与实现化解耦,使得二者可以独立变化,通过对象组合的方式,Bridge 模式把两个角色之间的继承关系改为了耦合的关系,从而使这两者可以从容自若的各自独立的变化,这是Bridge模式的本意,从而提高内聚度、降低藕合度。

源码链接:

https://github.com/GoodbyeLullaby/BridgeDemo

Guess you like

Origin www.cnblogs.com/smyhrps/p/12005582.html