目录
一、背景
- 在《对装饰器模式的理解》中,当我们想
基于
某个类做扩展时,我们不是采用继承而是组合的方式。这样,可以避免子类爆炸的问题。- 想象一下俄罗斯套娃,类与类之间的结果也类似。
- 还有一种场景:
- 如果采用继承的方式,例如,类型AB1、类型AB2等,也会导致子类爆炸。
- 那怎么解决呢? --> 依然是
组合
。
二、桥接模式的demo
1、类型A(形状类型)
java
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("circle");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("square");
}
}
2、类型B(颜色类型)
java
public interface Color {
void fill();
}
public class RedColor implements Color {
@Override
public String fill() {
return "red";
}
}
public class BlueColor implements Color {
@Override
public String fill() {
return "blue";
}
}
3、需求:类型A要使用类型B(如:红色的方形)
- 将类型A和类型B桥接起来。(本质上就是组合)
装饰器模式,是同一接口(同一抽象)的组合。
桥接模式,是不同接口(不同抽象)的组合。
- 实现:
java
public class Circle implements Shape {
private Color color;
public Circle(Color color) {
this.color = color;
}
@Override
public void draw() {
System.out.println(color.fill() + " circle");
}
}
public class Square implements Shape {
private Color color;
public Square(Color color) {
this.color = color;
}
@Override
public void draw() {
// System.out.println("square");
System.out.println(color.fill() + " square");
}
}
java
public class Application {
public static void main(String[] args) {
Shape redCircle = new Circle(new RedColor());
redCircle.draw();
Shape blueCircle = new Circle(new BlueColor());
blueCircle.draw();
System.out.println("-------------------------------");
Square redSquare = new Square(new RedColor());
redSquare.draw();
Square blueSquare = new Square(new BlueColor());
blueSquare.draw();
}
}
4、Spring的方式
实际开发中,我们希望Spring帮我们组织好bean,我们拿来就用即可。
java
@Configuration
public class ShapeConfig {
@Bean
public Color blueColor() {
return new BlueColor();
}
@Bean
public Color redColor() {
return new RedColor();
}
@Bean
public Square blueSquare(@Qualifier("blueColor") Color blueColor) {
return new Square(blueColor);
}
@Bean
public Square redSquare(@Qualifier("redColor") Color redColor) {
return new Square(redColor);
}
@Bean
public Circle blueCircle(@Qualifier("blueColor") Color blueColor) {
return new Circle(blueColor);
}
@Bean
public Circle redCircle(@Qualifier("redColor") Color redColor) {
return new Circle(redColor);
}
}
java
@ComponentScan
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Application.class);
Circle blueCircle = applicationContext.getBean("blueCircle", Circle.class);
blueCircle.draw();
Circle redCircle = applicationContext.getBean("redCircle", Circle.class);
redCircle.draw();
System.out.println("--------------------------------------------------------------------------------");
Square blueSquare = applicationContext.getBean("blueSquare", Square.class);
blueSquare.draw();
Square redSquare = applicationContext.getBean("redSquare", Square.class);
redSquare.draw();
applicationContext.close();
}
}