桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化
Abstraction
package design.pattern.bridge; public abstract class Abstraction { protected Implementor impl; public Abstraction(Implementor impl) { this.impl = impl; this.impl.setAbstraction(this); } public void operation() { impl.operation(); } }
Implementor
package design.pattern.bridge; public interface Implementor { public void operation(); public void setAbstraction(Abstraction abstraction); }
ConcreteAbstraction
package design.pattern.bridge; public class ConcreteAbstraction extends Abstraction { public ConcreteAbstraction(Implementor impl) { super(impl); } @Override public void operation() { System.out.println("ConcreteAbstraction do sth"); impl.operation(); } }
ConcreteImplementor
package design.pattern.bridge; public class ConcreteImplementor implements Implementor{ private Abstraction abstraction; public void setAbstraction(Abstraction abstraction) { this.abstraction = abstraction; } @Override public void operation() { System.out.println("ConcreteImplementor do sth with: " + abstraction); } }
Client
package design.pattern.bridge; public class Client { public static void main(String[] args) { new ConcreteAbstraction(new ConcreteImplementor()).operation(); } }