桥接模式

介绍

桥接模式, 抽象化与实现化解耦,使得二者可以独立变化

UML

 代码实现

public class BridgePatternDemo {
	public static void main(String[] args) {
		Shape shape1 = new Circle(new GreenCircle(), 1, 1, 1);
		Shape shape2 = new Circle(new RedCircle(), 1, 2, 1);
		shape1.draw();
		shape2.draw();
	}
}

/**
 * 图形绘制
 */
public interface DrawApi {	
	void drawCircle(int radius, int x, int y);
}

/**
 * 抽象的真正实现
 */
class RedCircle implements DrawApi {
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: red, radius: "+ radius +", x: " +x+", "+ y +"]");
   }
}

class GreenCircle implements DrawApi {
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: green, radius: "
         + radius +", x: " +x+", "+ y +"]");
   }
}
public abstract class Shape {
	//抽象对外的暴露,DrawApi 是真正需要实现的方法
	protected DrawApi drawApi;
	
	public Shape(DrawApi drawApi){
		this.drawApi = drawApi;
	}

	abstract public void draw();
}

/**
 * 虽然继承了,但是没有真正实现
 */
class Circle extends Shape {
	private final int x;
	private final int y;
	private final int redius;

	public Circle(DrawApi drawApi,int x,int y,int radius) {
		super(drawApi);
		this.x = x;
		this.y = y;
		this.redius = radius;
	}
	@Override
	public void draw() {
		drawApi.drawCircle(redius, x, y);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值