桥接模式(Bridge)——一个把 n*m 的问题转化为 n+m 的问题

定义

桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们都可以独立低变化。

再理解

我们可以把礼物从两个维度进行划分:给人的感觉、实物
给人的感觉就是抽象的,实物就是实现部分。

假如:
礼物给人的感觉有:温暖的礼物、冷漠的礼物、狂野的礼物。。。总过6种
礼物有:花、首饰两种。

正常理解,一个礼物,给人一种感觉,应该是要写在一个类的,所以:
按照正常来写,是:6*2=12个类

但是,桥接模式,把抽象和实现分开了。给人的感觉和礼物分开了,然后进行组合。就变成了 6+2=8个类了。

案例

假如,我是开礼品店的,我的礼品有花、首饰。我给礼品分的类有:给人感觉温暖的礼物、给人感觉冷漠的礼物。客户来购物时,按照这两个标准选礼物。

UML类图

桥接模式UML类图

代码

实现部分包括:IGift、Flower、Jewelry
IGift——礼物接口

package 桥接模式;

public interface IGift {
	
	void type();
}

Flower——礼物实现类1

package 桥接模式;

public class Flower implements IGift {

	@Override
	public void type() {
		System.out.println("花");
	}

}

Jewelry——礼物实现类1

package 桥接模式;

public class Jewelry implements IGift {

	@Override
	public void type() {
		System.out.println("首饰");
	}

}

抽象部分包括:父类Gift、WarmGift、ColdGift
Gift——礼物抽象父类

package 桥接模式;

public abstract class Gift {
	private IGift iGift;

	public Gift(IGift iGift) {
		super();
		this.iGift = iGift;
	}
	public void type() {
		iGift.type();
	}
}

WarmGift——礼物给人感觉类1

package 桥接模式;

public class WarmGift extends Gift{

	public WarmGift(IGift iGift) {
		super(iGift);
	}
	
	@Override
	public void type() {
		super.type();
		System.out.println("类型是温暖的");
	}
	
}

ColdGift——礼物给人感觉类2

package 桥接模式;

public class ColdGift extends Gift{

	public ColdGift(IGift iGift) {
		super(iGift);
	}
	
	@Override
	public void type() {
		super.type();
		System.out.println("类型是冰冷的");
	}
	
}

Client——客户

package 桥接模式;

public class Client {
	
	public static void main(String[] args) {
		
		Gift gift= new WarmGift(new Flower());
		gift.type();
		System.out.println("-----");
		Gift gift2= new WarmGift(new Jewelry());
		gift2.type();
		
		System.out.println("======");
		Gift gift3= new ColdGift(new Flower());
		gift3.type();
		System.out.println("-----");
		Gift gift4= new ColdGift(new Jewelry());
		gift4.type();
	}
}

运行结果

花
类型是温暖的
-----
首饰
类型是温暖的
======
花
类型是冰冷的
-----
首饰
类型是冰冷的

总结

  1. 实现了抽象和实现部分的分离,从而极大的提高了灵活性。
  2. 让抽象部分和实现部分分离,有助于系统分层设计,从而产生更好的结构化系统
  3. 对于系统的高层部分,只需要知道抽象部分和实现部分的接口就行了,其他部分由具体业务来完成
  4. 防止类爆炸

猜你喜欢

转载自blog.csdn.net/qq_42909053/article/details/106651235
nm