Table of Contents
Preface
Adapter pattern
Bridge mode
Home Java javaTutorial Introduction to Adapter Pattern and Bridge Pattern in Java Design Patterns (Code Example)

Introduction to Adapter Pattern and Bridge Pattern in Java Design Patterns (Code Example)

Sep 12, 2018 pm 04:02 PM
bridge mode adapter mode

This article brings you an introduction to the adapter mode and bridge mode in Java design patterns (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

Preface

In Previous article we learned about the builder pattern and prototype pattern of the creative pattern. In this article, we will learn about the adapter mode and bridge mode of structural mode.

Adapter pattern

Introduction

The Adapter pattern serves as a bridge between two incompatible interfaces. This type of design pattern is a structural pattern, which combines the functionality of two independent interfaces.

To put it simply, two incompatible classes are made compatible through an interface, commonly known as a converter.
A typical example in life is the voltage of electrical appliances. The voltage in the United States is about 110V, while the voltage in China is generally 220V. If we want to use American or Japanese electrical appliances, we need a converter to convert 110V to 220V. . Another typical example is the former universal charger, which can basically charge the batteries of various mobile phones.

Here we use a simple example to illustrate.
A certain video player can only play videos in MP4 format, but in addition to MP4, the mainstream video formats also include AVI, RVMB, etc. At this time, there is a software, Format Factory, which is used to convert video formats (adapter ) to play the video. At this time we can use the adapter pattern to complete the writing of the code.

There are two main types of adapter patterns. One is the class adapter pattern, which mainly implements adapter functions through inheritance; the other is the object adapter pattern, which implements adapter functions through combination.

First is the class adapter mode, which needs to complete the following steps:

  1. Establish an interface for MP4, AVI, RVMB video formats;

  2. Create a video player class to implement the MP4 video format class;

  3. Write a format factory class to convert video files in AVI, RVMB and other formats Convert to MP4 format files.

  4. Play these videos.

Then the code is as follows:

Code example:

    interface Mp4{
        void playMp4();
    }
    
    interface Avi{
        void playAvi();
    }
    
    
    interface Rvmb{
        void playRvmb();
    }
    
    class VideoPlayer implements Mp4{
    
        @Override
        public void playMp4() {
            System.out.println("播放Mp4格式的视频文件.");
        }
    }
    
    
    class FormatFactory extends VideoPlayer  implements Avi{    
        @Override
        public void playAvi() {
            //转换成MP4格式的视频
            playMp4();
        }
    }
    
    
    public static void main(String[] args) {        
            Mp4 mp4=new VideoPlayer();
            mp4.playMp4();
            Avi avi=new FormatFactory();
            avi.playAvi();
    }
Copy after login

Running result:

    播放Mp4格式的视频文件.
    播放Mp4格式的视频文件.
Copy after login

Through the above code and running results, we can get the desired results. If there are new video formats and we need to use the video player to play them, we only need to add an interface and format factory class. That's it.

Object Adapter Pattern
The adapter function is implemented through combination.
So here we only need to change the inheritance in the format factory to create an object.
The code after the change is as follows:
Code example

class FormatFactory2  implements Rvmb{
        private Mp4 mp4;
        
         public FormatFactory2(Mp4 mp4) {
            this.mp4=mp4;
        }
        
        @Override
        public void playRvmb() {
            mp4.playMp4();
        }   
    }


    public static void main(String[] args) {
    
            Rvmb rvmb=new FormatFactory2(new VideoPlayer());
            rvmb.playRvmb();
            
    }
Copy after login

Running results:

    播放Mp4格式的视频文件.
Copy after login

In these two adapter modes, All have implemented this function, but it is recommended to use the Object Adapter Pattern. Compared with the Class Adapter Pattern, it is more flexible and conforms to the synthesis and reuse principle in the design principles:

Try to use synthesis/aggregation instead of inheritance.

Advantages of the adapter pattern:

Improves the reuse and flexibility of classes.

Disadvantages of the adapter mode:

If used too much, the system will be messy and difficult to master.

Note:

The adapter is not added during detailed design, but to solve problems of the project in service.

Bridge mode

Introduction

Bridge is used to decouple abstraction and implementation so that the two can change independently. This type of design pattern is a structural pattern, which decouples abstraction and implementation by providing a bridging structure between them.

The literal interpretation is to connect things on both sides through a bridge in the middle, but the two related things do not affect each other. What impressed me most about this was the mobile phone brands and mobile phone software in <Dahua Design Pattern>. There are many brands of mobile phones, and there are many softwares on the market, and the software installed on each mobile phone is different. The brand includes software, but the software is not part of the mobile phone. They are an aggregation relationship. If brand A mobile phone is installed with software a and b, and brand B mobile phone is installed with software b and c, if brand A mobile phone needs to install a new software c, then it only needs to add the software without knowing how the software is produced. . Similarly, if a new C brand mobile phone is added, then it only needs to install the required a, b or c software.

Okay, let’s not talk too much nonsense, let’s still use an example to illustrate.
There are many kinds of pens on the market, such as pencils, black ballpoint pens, red ballpoint pens, etc. There are also many types of paper, such as paper for exam papers, newspaper paper, etc. Generally speaking, the color of the words on the newspaper is black. Here we use a black ballpoint pen to write. The color of the marking words on the examination paper is red. Here we use a red ballpoint pen to write. Pens and paper are independent of each other, but writing on paper associates them. Here we can use bridge mode.

实现步骤如下:

  1. 定义一个笔类的接口,有写的这个方法;

  2. 定义红笔和黑笔的类,实现笔类的接口;

  3. 定义一个纸类的抽象类,设置笔的种类,并需要实现被写的方法;

  4. 定义卷子纸和新闻纸类,继承纸类并实现该方法;

  5. 进行书写。

代码示例

interface Pen{
    void write();
}

class RedPen implements Pen{
    @Override
    public void write() {
        System.out.println("红色的字");
    }
}

class BlackPen implements Pen{
    @Override
    public void write() {
        System.out.println("黑色的字");
    }
}


abstract class  Paper{
    protected  Pen pen;
    
    void setPen(Pen pen){
        this.pen=pen;
    }   
    abstract void writing();
}

class ExaminationPaper extends Paper{
    @Override
    void writing() {
        pen.write();
    }
}

class NewsPaper extends Paper{
    @Override
    void writing() {
        pen.write();
    }
}

public static void main(String[] args) {
        Paper paper=new ExaminationPaper();
        paper.setPen(new RedPen());
        paper.writing();
        
        Paper paper2=new NewsPaper();
        paper2.setPen(new BlackPen());
        paper2.writing();
    }
Copy after login

运行结果

红色的字
黑色的字
Copy after login

从上述结果中我们可以得出我们想要的结果。如果新增一个笔类或者一个纸类,那么只需新增相应的接口和实现即可,并不会因为结构化改变而相互直接影响。

桥接模式的优点:

1、抽象和实现的分离,实现了解耦;
2、提升的扩展能力。

桥接模式的缺点:

会使系统看起复杂,对新手不友好,没有一定的抽象进行设计能力难以理解。

使用场景:

一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

相关推荐:

Java设计模式中建造者模式和原型模式的介绍(代码示例)

Java设计模式中工厂模式的介绍(代码示例)

The above is the detailed content of Introduction to Adapter Pattern and Bridge Pattern in Java Design Patterns (Code Example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles