search
HomeJavajavaTutorialDetailed explanation of bridge mode in Java design patterns

Detailed explanation of bridge mode in Java design patterns

Sep 22, 2017 am 11:22 AM
javamodelDesign Patterns

This article mainly introduces the bridge mode of Java design pattern, and analyzes the concept, function, Java implementation method and related precautions of the bridge mode in detail in the form of examples. Friends in need can refer to this article

The example describes the bridge mode of Java design pattern. Share it with everyone for your reference, as follows:

Concept:

Bridge Pattern: Separate the abstract part from its implementation part so that they are both Can vary independently.

The bridge mode converts inheritance relationships into association relationships, thereby reducing the coupling between classes and reducing the amount of code writing.

Under what circumstances will bridge mode be used?

To put it simply, when we abstract the characteristics of an object, the characteristic attributes of the object are very abstract, and we have to abstract the attributes again.

Otherwise, the number of specific subclasses will increase geometrically and will be difficult to expand. There is no way to maintain existing code.

For example, when we abstract the two objects of mobile phones, several of its attributes, such as operating system, CPU, screen, operator network, etc. are very complex. We cannot simply define these attributes directly, they must be abstracted again. A specific mobile phone object is a combination of these attributes, but it is not a simple combination. The attributes need to realize their own functions as attributes. Under such a design, code maintenance and expansion will be easier.

Note: When talking about this model, I cannot guarantee that the examples I say and write are correct. After all, I am new to it, and all examples are based on personal understanding.

I think the bridge mode description diagram:

The following is an example:

1. First define the abstract class, abstract and description object Characteristics.

Divide dimensions on the properties of the object for future bridging and expansion.


package test.design.bridge;
public abstract class CellPhone {
  private String cellPhoneName;
  public CellPhoneSystem cellPhoneSystem;
  public CellPhoneCPU cellPhoneCPU;
  public void works(){
    System.out.println("---------------------");
    System.out.println("This cellphone is:"+this.getCellPhoneName()+",welcome to use. ");
    System.out.println("This cellphone detail infomation:");
    System.out.println("系统类型:"+this.getCellPhoneSystem().getSystemName());
    System.out.println("cpu型号:"+this.getCellPhoneCPU().getCpuName());
    System.out.println("---------------------");
  }
  public String getCellPhoneName() {
    return cellPhoneName;
  }
  public void setCellPhoneName(String cellPhoneName) {
    this.cellPhoneName = cellPhoneName;
  }
  public CellPhoneSystem getCellPhoneSystem() {
    return cellPhoneSystem;
  }
  public void setCellPhoneSystem(CellPhoneSystem cellPhoneSystem) {
    this.cellPhoneSystem = cellPhoneSystem;
  }
  public CellPhoneCPU getCellPhoneCPU() {
    return cellPhoneCPU;
  }
  public void setCellPhoneCPU(CellPhoneCPU cellPhoneCPU) {
    this.cellPhoneCPU = cellPhoneCPU;
  }
}

2. Abstraction of attribute dimensions. (You can use interface definition, the key depends on your specific function)


package test.design.bridge;
/**
 * 属性cpu被抽象成一个维度,为了以后扩展
 * @author lushuaiyin
 *
 */
public abstract class CellPhoneCPU {
  public CellPhone cellPhone;
  public String cpuName;
  public void cpuWorks(){
    System.out.println("I am cpu. My pattern is:"+this.getCpuName());
    System.out.println("I am working for this cellphone:"+this.getCellPhone().getCellPhoneName());
  }
  public CellPhone getCellPhone() {
    return cellPhone;
  }
  public void setCellPhone(CellPhone cellPhone) {
    this.cellPhone = cellPhone;
    this.getCellPhone().setCellPhoneCPU(this);// 装配(桥接,或者可以认为对象类与其属性类的传递)
  }
  public String getCpuName() {
    return cpuName;
  }
  public void setCpuName(String cpuName) {
    this.cpuName = cpuName;
  }
}


package test.design.bridge;
/**
 * 属性操作系统被抽象成一个维度,为了以后扩展
 * @author lushuaiyin
 *
 */
public abstract class CellPhoneSystem {
  public CellPhone cellPhone;
  public String SystemName;
  public void systemWorks(){
    System.out.println("I am "+this.getSystemName()+" system.");
    System.out.println("I am working for this cellphone:"+this.getCellPhone().getCellPhoneName());
  }
  public CellPhone getCellPhone() {
    return cellPhone;
  }
  public void setCellPhone(CellPhone cellPhone) {
    this.cellPhone = cellPhone;
    this.getCellPhone().setCellPhoneSystem(this);// 装配(桥接,或者可以认为对象类与其属性类的传递)
  }
  public String getSystemName() {
    return SystemName;
  }
  public void setSystemName(String systemName) {
    SystemName = systemName;
  }
}

3. Specific dimension attribute object.

Here we define 2 specific objects each on the operating system attributes and cpu attributes,


package test.design.bridge;
public class AndroidSystem extends CellPhoneSystem{
}


package test.design.bridge;
public class IOSSystem extends CellPhoneSystem{
}


package test.design.bridge;
/**
 * 双核cpu
 * @author Administrator
 *
 */
public class TwoCore extends CellPhoneCPU{
}


package test.design.bridge;
/**
 * 四核cpu
 * @author Administrator
 *
 */
public class FourCore extends CellPhoneCPU{
}

4. Test the code.

It talks about how to expand the dimension when it is necessary to expand it.

Define a mobile phone object


##

package test.design.bridge;
public class Phone1 extends CellPhone{
  //具体对象的属性与逻辑
}

Test the main function


package test.design.bridge;
public class TestMain {
  /**
   * @param args
   */
  public static void main(String[] args) {
    //任何一种具体的对象都是复杂多种属性的集合,在此可以看出桥接模式在构建对象时的灵活性
    //产生一个具体对象1
    CellPhone p1=new Phone1();
    p1.setCellPhoneName(" IPhone 6 ");
    CellPhoneSystem system1=new IOSSystem();//操作系统属性维度
    system1.setSystemName("ios7");
    system1.setCellPhone(p1);//装配
    system1.systemWorks();//工作
    /*装配说的简单点就是传值。因为我们把一个对象的属性按维度分开来了,
     那么桥接的时候就必须相互传递对象。即对象类可以调用子属相类对象,
     子属性类对象也可以调用该对象类.
     关于这样的传值方式有多种,你可以在构造函数中传递,也可以在
    调用具体逻辑方法时传递。这里我直接用set方法传递,只是为了更清楚.
    如果某个属性维度是必须出现的,那就可以在抽象类的构造函数中传入*/
    CellPhoneCPU cpu1=new TwoCore();//cpu属性维度
    cpu1.setCpuName("A6");
    cpu1.setCellPhone(p1);
    cpu1.cpuWorks();
    p1.works();//最终整体对象功能
    /*
    桥接模式就是为了应对属性的扩展,在此说的属性必须是在维度确定的情况下。
    比如,这里我们在定义手机对象时,确定两个属性维度:操作系统和cpu型号。
    以后再这两个属性中,需要扩展时,就可以使用该模式。比如,一种新的cpu
    型号出现了,那么我不用重新设计现在的代码,只要增添一个cpu类即可。
    如果出现了新的维度属性,比如手机对象必须考虑屏幕大小。那桥接模式
    在此就需要从根本上修改代码来了。
    */
    System.out.println("-----------分割---------------------------");
    //在cpu维度上扩展。比如出现新型cpu:8核三星Exynos 5 Octa芯片".
    //三星手机推出了GALAXY Note Ⅲ就是使用这种新型cpu. 写一个新类EightCore扩展cpu维度.
    //同时定义这个手机对象GALAXY Note Ⅲ为PhoneGalaxyNote3
    CellPhone note3=new PhoneGalaxyNote3();
    note3.setCellPhoneName("GALAXY Note Ⅲ");
    CellPhoneSystem system2=new AndroidSystem();
    system2.setSystemName("android4");
    system2.setCellPhone(note3);//装配
    system2.systemWorks();//工作
    CellPhoneCPU cpu2=new EightCore();//最新8核cpu
    cpu2.setCpuName("三星Exynos 5 Octa芯片");
    cpu2.setCellPhone(note3);
    cpu2.cpuWorks();
    note3.works();//三星GALAXY Note Ⅲ新体验
  }
}

If you need to extend it, define New dimension attribute


package test.design.bridge;
public class EightCore extends CellPhoneCPU {
}


package test.design.bridge;
public class PhoneGalaxyNote3 extends CellPhone{
  //具体对象的属性与逻辑
}

Test print;


I am ios7 system.
I am working for this cellphone: IPhone 6
I am cpu. My pattern is:A6
I am working for this cellphone: IPhone 6
---------------------
This cellphone is: IPhone 6 ,welcome to use.
This cellphone detail infomation:
系统类型:ios7
cpu型号:A6
---------------------
-----------分割---------------------------
I am android4 system.
I am working for this cellphone:GALAXY Note Ⅲ
I am cpu. My pattern is:三星Exynos 5 Octa芯片
I am working for this cellphone:GALAXY Note Ⅲ
---------------------
This cellphone is:GALAXY Note Ⅲ,welcome to use.
This cellphone detail infomation:
系统类型:android4
cpu型号:三星Exynos 5 Octa芯片
---------------------

The above is the detailed content of Detailed explanation of bridge mode in Java design patterns. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to safely store JavaScript objects containing functions and regular expressions to a database and restore?How to safely store JavaScript objects containing functions and regular expressions to a database and restore?Apr 19, 2025 pm 11:09 PM

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

Do Android development need to learn Kotlin?Do Android development need to learn Kotlin?Apr 19, 2025 pm 11:03 PM

Is Kotlin worth learning? Does Android development require Kotlin? Many Android developers will have questions when using Java for development: Kotlin language...

Where exactly is the JVM string constant pool stored?Where exactly is the JVM string constant pool stored?Apr 19, 2025 pm 11:00 PM

In-depth discussion on the storage location of JVM string constant pools This article will provide a detailed answer to a question about the storage location of JVM string constant pools. Someone mentioned...

In a multi-node environment, how to ensure that Spring Boot's @Scheduled timing task is executed only on one node?In a multi-node environment, how to ensure that Spring Boot's @Scheduled timing task is executed only on one node?Apr 19, 2025 pm 10:57 PM

The optimization solution for SpringBoot timing tasks in a multi-node environment is developing Spring...

Under the Nacos Registration Center, how does OpenFeign implement cross-namespace microservice calls?Under the Nacos Registration Center, how does OpenFeign implement cross-namespace microservice calls?Apr 19, 2025 pm 10:54 PM

Nacos Registration Center and OpenFeign Cross-namespace Call This article discusses how to use OpenFeign to implement microservices in different namespaces in Nacos Registration Center...

What is the difference between the two types of consistency consensus algorithms? What are the specific implementations?What is the difference between the two types of consistency consensus algorithms? What are the specific implementations?Apr 19, 2025 pm 10:51 PM

Understanding the key points of two types of consensus algorithms When discussing consistency consensus algorithms, we often mention that there has been no new choice at the protocol level for a long time...

How to process and display percentage numbers in Java?How to process and display percentage numbers in Java?Apr 19, 2025 pm 10:48 PM

Display and processing of percentage numbers in Java In Java programming, the need to process and display percentage numbers is very common, for example, when processing Excel tables...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool