核心模块:Abstracttion抽象类、RefinedAbstraction扩充抽象类、Implementor实现类接口、ConcreteImplementor具体实现类
所有代码请访问:git@code.aliyun.com:289804201/PatternLearn.git
使用场景:多维度耦合的情况,不希望用继承的情况;
优点:减少了类的数量和和代码量,避免了指数增长,每个维度的扩展性都很好;
缺点:对开发者抽象能力要求高,适用范围小;
注意:
1,将多个维度的父类提取出来,在抽象层耦合;
2,一般来说,每一个维度要维护一个上一个维度的对象指针,第一个维度除外;
3,区别于装饰者模式,装饰者模式装饰者和被装饰者都实现同一个抽象构件,本质上是同一个维度,同一个事物的修饰扩展;而桥接模式是同一类(同一维度)不同个体的扩展,并且可以多个维度扩展;
/**
* Created by tory on 2018/1/10.
*/
public class BridgePattern {
public static void main(String[] args) {
Color red = new Red();
Color sliver = new Sliver();
Laptop laptop = new Laptop();
Desktop desktop = new Desktop();
Acer acer = new Acer();
desktop.setColor(red);
acer.setType(desktop);
acer.build();
Apple apple = new Apple();
laptop.setColor(sliver);
apple.setType(laptop);
apple.build();
Dell dell = new Dell();
laptop.setColor(new Dark());
dell.setType(laptop);
dell.build();
}
}
//Implementor实现类接口,仅提供基本操作
interface Color {
//第一个维度,电脑颜色
String paint();
}
//Abstracttion抽象类,维护一个指向Implementor类型对象的指针
abstract class Type {
//第二个维度,电脑类型
Color color;
void setColor(Color color) {
this.color = color;
}
abstract void type();
}
//RefinedAbstraction扩充抽象类
abstract class Manufactur {
//第三个维度,电脑厂商
Type type;
void setType(Type type) {
this.type = type;
}
abstract void build();
}
//ConcreteImplementor 具体实现类
class Red implements Color {
public String paint() {
// System.out.print("红色的");
return "红色的";
}
}
//ConcreteImplementor 具体实现类
class Sliver implements Color {
@Override
public String paint() {
return "银色的";
}
}
//ConcreteImplementor 具体实现类
class Pink implements Color {
@Override
public String paint() {
return "粉红色的";
}
}
//ConcreteImplementor 具体实现类
class Dark implements Color {
@Override
public String paint() {
return "黑色的";
}
}
class Desktop extends Type {
//第二个维度扩展,台式机
@Override
void type() {
System.out.println(color.paint() + "台式机");
}
}
class Laptop extends Type {
//第二个维度扩展,台式机
@Override
void type() {
// color.paint();
System.out.println(color.paint() + "笔记本");
}
}
class Acer extends Manufactur {
//第三个维度扩展,Acer
@Override
void build() {
System.out.println("Acer 生产了 一台");
type.type();
}
}
class Apple extends Manufactur {
@Override
void build() {
System.out.println("Apple 生产了 一台");
type.type();
}
}
class Dell extends Manufactur {
@Override
void build() {
System.out.println("Dell 生产了 一台");
type.type();
}
}
内容打印
Hello World!
Acer 生产了 一台
红色的台式机
Apple 生产了 一台
银色的笔记本
Dell 生产了 一台
黑色的笔记本