1、画圆接口

package Bridge;

public interface DrawAPI {

	public void drawCircle(int radius, int x, int y);

}

  

2、画圆接口实现类——绿圆

package Bridge;

public class GreenCircle implements DrawAPI{

	@Override
	public void drawCircle(int radius, int x, int y) {
		System.out.println("Drawing Circle[ color: green, radius: "
				+ radius +", x: " +x+", "+ y +"]");
	}

	
}

 

3、画圆接口实现类——红圆

 

package Bridge;

public class RedCircle implements DrawAPI{

	@Override
	public void drawCircle(int radius, int x, int y) {
		System.out.println("Drawing Circle[ color: red, radius: "
				+ radius +", x: " +x+", "+ y +"]");
	}

}

  

4、形状父类

 

package Bridge;

public abstract class Shape {

	public abstract void draw();
	
}

  

5、形状子类

 

package Bridge;

public class Circle extends Shape{

	protected DrawAPI drawAPI;
	private int x, y, radius;
	
	public Circle(int x, int y, int radius, DrawAPI drawAPI) {

		this.drawAPI = drawAPI;
		this.x = x;
		this.y = y;
		this.radius = radius;
		
	}
	
	public void draw(){
		drawAPI.drawCircle(radius, x, y);
	}

}

  在Circle类中引用DrawAPI 的对象,即可使用DrawAPI 的实现类:

  GreenCircleRedCircle ,完成桥接

 

6、测试类

package Bridge;

public class BridgePatternDemo {

	public static void main(String[] args) {
		
		Shape redCircle = new Circle(100,100,10,new RedCircle());
		
		Shape greenCircle = new Circle(100,100,10,new GreenCircle());
		
		redCircle.draw();	//调用了RedCircle的draw()
		greenCircle.draw();	//调用了GreenCircle的draw()
	}
}

  

 

 测试结果:

Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]

 

 ————————————————————————————————————————————————

修改上面第四个和第五个Shape类和Circle类,效果相同:

 

4、形状父类

package Bridge;

public abstract class Shape {

    protected DrawAPI drawAPI;
    
    protected Shape(DrawAPI drawAPI){
        this.drawAPI = drawAPI;
    }
    
    public abstract void draw();
    
}

  

  在Shape类中引用DrawAPI 的对象,即可使用DrawAPI 的实现类:

  GreenCircle RedCircle ,完成桥接

 

 

5、形状子类

package Bridge;

public class Circle extends Shape{

    private int x, y, radius;
    
    public Circle(int x, int y, int radius, DrawAPI drawAPI) {
        super(drawAPI);
        this.x = x;
        this.y = y;
        this.radius = radius;
        
    }
    
    public void draw(){
        drawAPI.drawCircle(radius, x, y);
    }

}

 

 posted on 2017-10-09 16:51  布鲁布鲁sky  阅读(147)  评论(0编辑  收藏  举报