Java Advanced design mode four------adapter mode and bridge mode

Source: Internet
Author: User

Objective

In the previous article, we learned about the builder pattern and prototype pattern of the creation pattern. This article is to learn the structure mode of the adapter mode and bridge mode.

Adapter mode

Brief introduction

The adapter mode is a bridge between two incompatible interfaces. This type of design pattern belongs to the structural pattern, which combines the functions of two separate interfaces.

In simple terms, an incompatible two class is compatible with an interface, commonly known as a converter.
Typical example of life is the electrical voltage, the U.S. voltage is about 110V, and China's voltage is 220V, if we want to use the United States or Japan's electrical appliances, you need a converter to convert 110V to 220V. There is also a very typical example is the ever-universal charger, the basic can be filled with a variety of cell phone battery.

Here we use a simple example to illustrate.
A video player, can only play MP4 format video, but the mainstream video format in addition to MP4, as well as AVI, RVMB, and so on, there is a software, format factory for the video format conversion (adapter), so as to play video. At this point we can use the adapter pattern to complete the writing of the Code.

There are two main types of adapter mode, one is the class adapter mode, the adapter function is implemented mainly through inheritance, and the other is the object adapter mode, which realizes the adapter function by combining.

The first is the class adapter pattern , which needs to complete the steps:

    1. Establish the interface of MP4, AVI, RVMB video format;
    2. Set up 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 into 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();    }

Operation Result:

    播放Mp4格式的视频文件.    播放Mp4格式的视频文件.

With the above code and the results of the operation, we can get the desired result, if there is a new video format, also need to play with the video player, just add an interface and the format of the factory class can be.

Object Adapter Mode
The adapter functionality is implemented by combining them.
So here we just change the inheritance of the format factory to create the 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();                }

Operation Result:

    播放Mp4格式的视频文件.

Both of these adapter modes implement this feature, but it is recommended to use the object Adapter mode, which is more flexible than the class adapter mode and conforms to the principle of synthetic reuse in design principles:

Use compositing/aggregation as much as possible, rather than using inheritance.

Advantages of the adapter mode:

Improves the reuse and flexibility of classes.

Disadvantages of Adapter mode:

Use too much, the system will be more cluttered, difficult to grasp.

Precautions:

The adapter is not added at the detailed design time, but instead solves the problem of the project in service.

Bridging mode

Brief introduction

Bridging is used to decouple abstraction from implementation so that they can change independently. This type of design pattern belongs to the structural model, which realizes decoupling by providing the bridging structure between abstraction and implementation.

The literal meaning of the interpretation is through an intermediate bridge to the two sides of the thing connected, but the correlation between the other does not affect each other. The impression is more deep <大话设计模式> in the mobile phone brand and mobile phone software, mobile phones have many brands, the market has a lot of software, each phone installed software is different, the mobile phone brand contains software, but the software is not part of the phone, they are the aggregation relationship. If a brand mobile phone loaded with a, B software, brand-name mobile phone installed b,c software, if a brand phone needs to install a new C software, then it only need to add the software, do not need to know how the software is produced. Similarly, if a C-branded phone is added, it can only install the required a, B, or C software.

Well, the nonsense is not much to say, still use an example to illustrate.
There are many kinds of pens in the market, such as pencils, black ballpoint pens and red ballpoint pens, etc., there are also many kinds of paper, such as paper used for examination, newspaper paper and so on. Generally speaking, the color of the newspaper is black, here we use Black ballpoint pen to write, test paper on the color of the word is red, here we use Red ballpoint pen to write. Pens and paper are independent of each other, but writing on paper and associating them together, we can use bridging mode here.

The implementation steps are as follows:

    1. Defines an interface for a pen class, with this method of writing;
    2. Define the class of red pen and black pen, implement the interface of PEN class;
    3. Define a paper class abstract class, set the type of pen, and need to implement the method to be written;
    4. Define paper and newsprint, inherit paper and implement the method;
    5. To write.

code example

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();    }

Run results

红色的字黑色的字

From the above results we can draw the result we want. If you add a pen class or a paper class , you only need to add the corresponding interface and implementation, and will not be directly affected by the structural changes.

Advantages of Bridging Mode:

1, the separation of abstraction and realization, the realization of understanding coupling;
2, the expansion capacity of the promotion.

Disadvantages of Bridging Mode:

will make the system look complicated, unfriendly to the novice, not a certain abstraction of the design ability is difficult to understand.

Usage scenarios:

There are two independently varying dimensions for a class, and these two dimensions need to be expanded.

Other music recommendations

NetEase Cloud Netizen Evaluation (PS: The original can not generate outside the chain, recommended to listen to the original):

Hibiscus painter Shallow Brook, living in Taian, Xi-painted carp. The former side of the Lotus pond, koi swimming, brook often and play. Its time is the chaos of the clan, the war is frequent, 魑魅魍魉, the contrary to the Tao. Bingge forced Taian, street neighbors are fleeing, alone Brook not shed brocade carp, not go. It was night, and the hospital room was in flames. Someone into the fire to protect the brook, said its native carp in the demon, want to take the brook life, but born sincere feelings, then can't bear for it. The next day the fire ceased, and the man was gone.

Original is not easy, if feel good, hope to give a recommendation! Your support is my greatest motivation for writing!
Copyright Notice:
Empty Realm
Blog Park Source: http://www.cnblogs.com/xuwujing
CSDN Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com

Java Advanced design mode four------adapter mode and bridge mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.