Home > Java > javaTutorial > body text

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

不言
Release: 2018-09-12 16:02:39
Original
1662 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!