Java设计模式:桥接模式

版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/88721704

public interface Sourceable {
	void method();
}

public class Source1 implements Sourceable{

	@Override
	public void method() {
		System.out.println("Source1 method");
	}

}

public class Source2 implements Sourceable{

	@Override
	public void method() {
		System.out.println("Source2 method");
	}
}
public abstract class Bridge {
	private Sourceable source;

	public void bridgeMethod() {
		source.method();
	}

	public Sourceable getSource() {
		return source;
	}

	public void setSource(Sourceable source) {
		this.source = source;
	}
}

public class MyBridge extends Bridge {
	@Override
	public void bridgeMethod() {
		getSource().method();
	}
}
public class Test {
	public static void main(String[] args) {
		try {
			Test test = new Test();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Test() {
		Bridge bridge = new MyBridge();

		Sourceable source1 = new Source1();
		bridge.setSource(source1);
		bridge.bridgeMethod();

		Sourceable source2 = new Source2();
		bridge.setSource(source2);
		bridge.bridgeMethod();
	}
}

输出:

Source1 method
Source2 method

桥接模式最典型的使用是JDBC数据库连接,如图:

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/88721704
今日推荐