1.8 (Design mode) bridge mode

Bridge mode may be implemented abstract and separated, the two can interfere with each other changes alone.

It is connected by a bridge between them, so called bridge mode.

 

The following give a concrete example, assume the Shape There is an abstract class, there are some implementation class RedCircle, GreenCircle.

An interface connected between them through a bridge DrawAPI.

 

 

 

Interface bridge (bridge Bridge mode)

public interface DrawAPI {
    public void drawCircle(float r,float x, float y);
}

 

To implement a specific category bridge interface (implemented section bridging mode)

GreenCircle

public class GreenCircle implements DrawAPI{

    @Override
    public void drawCircle(float r, float x, float y) {
        System.out.println("draw greenCircle" + "r:" + r +" x:" + x + " y:" + y);
    }

}

 

RedCircle

public class RedCircle implements DrawAPI{

    @Override
    public void drawCircle(float r, float x, float y) {
        System.out.println("draw redCircle" + "r:" + r +" x:" + x + " y:" + y);
    }
}

 

 

Shape (Abstract section bridging mode) using the Shape DrawAPI (bridge)

public  abstract  class the Shape {
     protected DrawAPI drawAPI; 
    
    public the Shape (DrawAPI drawAPI) {   // abstract classes are classes, but can not be instantiated by itself, 
        the this .drawAPI = drawAPI;       // typically by sub-class is instantiated (called by default constructor with no arguments method), if you add a constructor you will need to reference subclasses. 
    } 
    
    Public  abstract  void Draw (); 
}

 

 

Circle: Shape concrete class

public class Circle extends Shape{
    private float r;
    private float x;
    private float y;
    
    
    public Circle(float r, float x, float y,DrawAPI drawAPI) {
        super(drawAPI);
        // TODO Auto-generated constructor stub
        this.r = r;
        this.x = x;
        this.y = y;
    }

    @Override
    public void draw() {
        // TODO Auto-generated method stub
        drawAPI.drawCircle(r, x, y);
    }
}

 

test:

public class Main {
    public static void main(String[] args) {
        Shape greenCircle = new Circle(2, 0, 0, new GreenCircle());
        greenCircle.draw();
        Shape redCircle = new Circle(2, 0, 0, new RedCircle());
        redCircle.draw();
    }
}
draw greenCircler:2.0 x:0.0 y:0.0
draw redCircler:2.0 x:0.0 y:0.0

 

Between the abstract and the connection is achieved by a bridge, the transformation between abstraction independently and achieve a specific category change does not affect the abstract class.

Nor will it change the abstract class to achieve impact class, as long as the bridge connecting the two did not change, both of which can be independently transformed and easy to expand.

 

Guess you like

Origin www.cnblogs.com/huang-changfan/p/10950133.html