23种设计模式之桥接模式
桥接(Bridge)模式的定义如下:将抽象与实现分离,使它们可以独立变化。它是用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。
桥接模式实例一
桥接(Bridge)模式包含以下主要角色。
抽象化(Abstraction)角色:定义抽象类,并包含一个对实现化对象的引用。
扩展抽象化(Refined Abstraction)角色:是抽象化角色的子类,实现父类中的业务方法,并通过组合关系调用实现化角色中的业务方法。
实现化(Implementor)角色:定义实现化角色的接口,供扩展抽象化角色调用。
具体实现化(Concrete Implementor)角色:给出实现化角色接口的具体实现。
图解
代码
//实现化角色
interface Implementor
{
public void OperationImpl();
}
//具体实现化角色
class ConcreteImplementorA implements Implementor
{
public void OperationImpl()
{
System.out.println("具体实现化(Concrete Implementor)角色被访问" );
}
}
//抽象化角色
abstract class Abstraction
{
protected Implementor imple;
protected Abstraction(Implementor imple)
{
this.imple=imple;
}
public abstract void Operation();
}
//扩展抽象化角色
class RefinedAbstraction extends Abstraction
{
protected RefinedAbstraction(Implementor imple)
{
super(imple);
}
public void Operation()
{
System.out.println("扩展抽象化(Refined Abstraction)角色被访问" );
imple.OperationImpl();
}
}
public class BridgeTest
{
public static void main(String[] args)
{
Implementor imple=new ConcreteImplementorA();
Abstraction abs=new RefinedAbstraction(imple);
abs.Operation();
}
}
结果
桥接模式实例二
代码
public abstract class Shape {
Color color;
public void setColor(Color color) {
this.color = color;
}
public abstract void draw();
}
class Circle extends Shape{
public void draw() {
color.bepaint("正方形");
}
}
class Rectangle extends Shape{
public void draw() {
color.bepaint("长方形");
}
}
class Square extends Shape{
public void draw() {
color.bepaint("正方形");
}
}
interface Color {
public void bepaint(String shape);
}
class White implements Color{
public void bepaint(String shape) {
System.out.println("白色的" + shape);
}
}
class Gray implements Color{
public void bepaint(String shape) {
System.out.println("灰色的" + shape);
}
}
class Black implements Color{
public void bepaint(String shape) {
System.out.println("黑色的" + shape);
}
}
class Client {
public static void main(String[] args) {
//白色
Color white = new White();
//正方形
Shape square = new Square();
//白色的正方形
square.setColor(white);
square.draw();
//长方形
Shape rectange = new Rectangle();
rectange.setColor(white);
rectange.draw();
}
}
结果