Detailed explanation of Bridge mode

In real life, some classes have two or more dimensions of change, such as graphics can be divided by shape and color. How to design software like Photoshop that can draw different shapes and colors? If we use inheritance method, there are m × n kinds of M shapes and n colors, which not only correspond to many subclasses, but also are difficult to expand.

Of course, there are many other examples, such as text of different colors and fonts, cars of different brands and powers, men and women of different genders and professions, media players supporting different platforms and file formats, etc. If we use the bridge mode, we can solve these problems well.

The definition and characteristics of bridge mode

The Bridge pattern is defined as follows: separating abstractions from implementations so that they can change independently. It is realized by using combination relation instead of inheritance relation, which reduces the coupling degree of abstraction and realization.

The advantages of Bridge mode are:

  • Because of the separation of abstraction and implementation, it has strong expansibility;
  • The implementation details are transparent to customers.

The disadvantage is: because the aggregation relationship is based on the abstraction layer, developers are required to design and program for abstraction, which increases the difficulty of system understanding and design.

Structure and implementation of bridge mode

We can separate the abstract part from the implementation part, cancel their inheritance relationship, and use the combination relationship instead.
1. Structure of mode

The Bridge mode consists of the following main roles.

  • Abstraction role: defines an abstract class and contains a reference to an implementation object.
  • Extended abstraction role: it is a subclass of the abstract role, which implements the business methods in the parent class, and realizes the business methods in the role through the composite relation call.
  • Implementor role: defines the interface of the implementer role, which can be called by the extended abstract role.
  • Concrete Implementor role: the concrete implementation of the role interface is given.

The structure diagram is shown in Figure 1.

Figure 1 Structure of bridge mode
2. Implementation of the pattern

The code for the bridge mode is as follows:

package bridge;
public class BridgeTest
{
    public static void main(String[] args)
{
        Implementor imple=new ConcreteImplementorA();
        Abstraction abs=new RefinedAbstraction(imple);
        abs.Operation();
    }
}
//Realized role
interface Implementor
{
    public void OperationImpl();
}
//Specific realization role
class ConcreteImplementorA implements Implementor
{
    public void OperationImpl()
{
        System.out.println("Concrete realization(Concrete Implementor)Role accessed" );
    }
}
//Abstract role
abstract class Abstraction
{
   protected Implementor imple;
   protected Abstraction(Implementor imple)
{
       this.imple=imple;
   }
   public abstract void Operation();   
}
//Extend Abstract roles
class RefinedAbstraction extends Abstraction
{
   protected RefinedAbstraction(Implementor imple)
{
       super(imple);
   }
   public void Operation()
{
       System.out.println("Extension abstraction(Refined Abstraction)Role accessed" );
       imple.OperationImpl();
   }
}

The running results of the program are as follows:

The defined abstraction role is accessed
 Concrete implementor role is accessed

Application example of bridge mode

[example 1] use Bridge mode to simulate the purchase of women's leather bags.

Analysis: there are many kinds of women's leather bags, which can be divided by use, leather, brand, color, size, etc. there are many dimensional changes, so it is more appropriate to use the bridging mode to achieve the purchase of women's leather bags.

This example can be divided into Wallet and HandBag by use, Yellow and Red by color. It can be defined as color class and package class according to two dimensions.
Color class is a dimension defined as an implementation role. It has two specific implementation roles: yellow and red. Color can be selected through getColor() method; Bag is another dimension defined as an abstraction role. It has two extended abstraction roles: satchel and wallet. It contains color class objects through getName() Method: you can choose the relevant color of the Bag and wallet.

The customer class obtains the package information from the XML configuration file through the ReadXML class, and displays the selected product through the window, as shown in Figure 2.

Figure 2 structure of women's leather bag purchase

The program code is as follows:

package bridge;
import java.awt.*;
import javax.swing.*;
public class BagManage
{
    public static void main(String[] args)
{
        Color color;
        Bag bag;
        color=(Color)ReadXML.getObject("color");
        bag=(Bag)ReadXML.getObject("bag");
        bag.setColor(color);
        String name=bag.getName();
        show(name);
    }
    public static void show(String name)
{
        JFrame jf=new JFrame("Bridge mode test");
        Container contentPane=jf.getContentPane();
        JPanel p=new JPanel();   
        JLabel l=new JLabel(new ImageIcon("src/bridge/"+name+".jpg"));
        p.setLayout(new GridLayout(1,1));
        p.setBorder(BorderFactory.createTitledBorder("Ladies leather bag"));
        p.add(l);
        contentPane.add(p, BorderLayout.CENTER);
        jf.pack();  
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
//Materialized character: color
interface Color
{
    String getColor();
}
//Specific realization role: yellow
class Yellow implements Color
{
    public String getColor()
{
        return "yellow";
    }
}
//Specific realization role: Red
class Red implements Color
{
    public String getColor()
{
        return "red";
    }
}
//Abstract role: package
abstract class Bag
{
    protected Color color;
    public void setColor(Color color)
{
        this.color=color;
    }   
    public abstract String getName();
}
//Extended abstract role: sidebag
class HandBag extends Bag
{
    public String getName()
{
        return color.getColor()+"HandBag";
    }   
}
//Extended abstract role: wallet
class Wallet extends Bag
{
    public String getName()
{
        return color.getColor()+"Wallet";
    }   
}
package bridge;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
class ReadXML
{
    public static Object getObject(String args)
    {
        try
        {
            DocumentBuilderFactory dFactory=DocumentBuilderFactory.newInstance();
            DocumentBuilder builder=dFactory.newDocumentBuilder();
            Document doc;                           
            doc=builder.parse(new File("src/bridge/config.xml"));
            NodeList nl=doc.getElementsByTagName("className");
            Node classNode=null;
            if(args.equals("color"))
            {
                classNode=nl.item(0).getFirstChild();
            }
            else if(args.equals("bag"))
            {
                classNode=nl.item(1).getFirstChild();
            }          
            String cName="bridge."+classNode.getNodeValue();
            Class<?> c=Class.forName(cName);
              Object obj=c.newInstance();
            return obj;
        }  
        catch(Exception e)
        {
               e.printStackTrace();
               return null;
        }
    }
}

If you modify the XML configuration file as follows:

<?xml version="1.0" encoding="UTF-8"?>
<config>
<className>Red</className>
<className>Wallet</className>
</config>

Application scenario of bridge mode

The bridge mode is generally suitable for the following scenarios.

  • When a class has two independent changing dimensions and both dimensions need to be extended.
  • When a system does not want to use inheritance or the number of system classes increases sharply due to multi-level inheritance.
  • When a system needs to add more flexibility between the abstract and concrete roles of components.

The extension of bridge mode mode

In software development, sometimes the Bridge pattern can be used in combination with the adapter pattern. When the interface of the implementation role of the Bridge pattern is inconsistent with the interface of the existing class, an adapter can be defined between the two to connect them, and the specific structure diagram is shown in Figure 3.

Figure 3 structure of bridge mode and adapter mode

97 original articles published, praised 128, visited 40000+
Private letter follow

Tags: xml Java encoding

Posted on Sat, 07 Mar 2020 03:46:23 -0800 by stc7outlaw