桥接模式

个人博客

http://www.milovetingting.cn

桥接模式

模式介绍

桥接模式也称为桥梁模式,是结构型设计模式之一。

模式定义

将抽象部分与实现部分分离,使它们都可以独立地进行变化。

使用场景

  1. 一个系统需要在构件的抽象化角色和具体角色之间增加更多灵活性,避免在两个层次之间建立静态的继承关系,可以通过桥接模式使它们在抽象层建立一个关联关系。

  2. 不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统。

  3. 一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

简单使用

定义抽象类

public abstract class CoffeeAdditives {
	public abstract String addSomething();
}

定义实现类

public class Sugar extends CoffeeAdditives {

	@Override
	public String addSomething() {
		return "加糖";
	}

}

public class Ordinary extends CoffeeAdditives{

	@Override
	public String addSomething() {
		return "原味";
	}

}

定义抽象类

public abstract class Coffee {

	protected CoffeeAdditives coffeeAdditives;

	public Coffee(CoffeeAdditives coffeeAdditives) {
		super();
		this.coffeeAdditives = coffeeAdditives;
	}

	public abstract void makeCoffee();

}

定义实现类

public class LargeCoffee extends Coffee {

	public LargeCoffee(CoffeeAdditives coffeeAdditives) {
		super(coffeeAdditives);
	}

	@Override
	public void makeCoffee() {
		System.out.println("大杯的" + coffeeAdditives.addSomething() + "咖啡");
	}

}

public class SmallCoffee extends Coffee {

	public SmallCoffee(CoffeeAdditives coffeeAdditives) {
		super(coffeeAdditives);
	}

	@Override
	public void makeCoffee() {
		System.out.println("小杯的" + coffeeAdditives.addSomething() + "咖啡");
	}

}

调用

public class Main {

	public static void main(String[] args) {
		Ordinary ordinary = new Ordinary();

		Sugar sugar = new Sugar();

		LargeCoffee largeCoffee = new LargeCoffee(ordinary);
		largeCoffee.makeCoffee();

		SmallCoffee smallCoffee = new SmallCoffee(ordinary);
		smallCoffee.makeCoffee();

		LargeCoffee largeCoffee2 = new LargeCoffee(sugar);
		largeCoffee2.makeCoffee();

		SmallCoffee smallCoffee2 = new SmallCoffee(sugar);
		smallCoffee2.makeCoffee();

	}

}

输出结果

大杯的原味咖啡
小杯的原味咖啡
大杯的加糖咖啡
小杯的加糖咖啡
原文地址:https://www.cnblogs.com/milovetingting/p/12329534.html