我是否正确地解开了Bridge Pattern:
BEFORE:
public class Main2 {
@SuppressWarnings("unused")
public static void main(String[] args) {
Car car11 = new BadNativeCar();
Car car12 = new GoodNativeCar();
Car car21 = new BadForeignCar();
Car car22 = new GoodForeignCar();
}
}
interface Car{
public void drive();
public void stop();
}
class NativeCar implements Car{
@Override
public void drive() {
}
@Override
public void stop() {
}
}
class ForeignCar implements Car{
@Override
public void drive() {
}
@Override
public void stop() {
}
}
class GoodNativeCar extends NativeCar{
}
class BadNativeCar extends NativeCar{
}
class GoodForeignCar extends ForeignCar{
}
class BadForeignCar extends ForeignCar{
}
AFTER(BRIDGE):
public class Main2 {
public static void main(String[] args) {
BadCar badCar = new BadCar();
GoodCar goodCar = new GoodCar();
CarAbstraction car11 = new NativeCar(badCar);
CarAbstraction car12 = new NativeCar(goodCar);
CarAbstraction car21 = new ForeignCar(badCar);
CarAbstraction car22 = new ForeignCar(goodCar);
}
}
interface CarAbstraction{
public void drive();
public void stop();
}
//Abstraction
abstract class CarAbstractionImpl implements CarAbstraction{
private CarImplementor carImplementor;
public CarAbstractionImpl(CarImplementor carImplementor) {
this.carImplementor = carImplementor;
}
@Override
public void drive() {
carImplementor.drive();
}
@Override
public void stop() {
carImplementor.stop();
}
}
//RefinedAbstraction1
class NativeCar extends CarAbstractionImpl{
public NativeCar(CarImplementor carImplementor) {
super(carImplementor);
}
}
//RefinedAbstraction2
class ForeignCar extends CarAbstractionImpl{
public ForeignCar(CarImplementor carImplementor) {
super(carImplementor);
}
}
//Implementor
interface CarImplementor extends CarAbstraction{
}
//ConcreteImplementor1
class GoodCar implements CarImplementor{
@Override
public void drive() {
}
@Override
public void stop() {
}
}
//ConcreteImplementor2
class BadCar implements CarImplementor{
@Override
public void drive() {
}
@Override
public void stop() {
}
}
答案 0 :(得分:2)
根据你的问题,我得到了以下类图:
<强> BEFORE:强>
________Car_________
/ \
NativeCar ForeignCar
/ \ / \
GoodNativeCar BadNativeCar GoodForeignCar BadForeignCar
<强> AFTER:强>
CarAbstraction
|
CarAbstractionImpl-------------HAS-A-------> CarImplementor
/ \ / \
NativeCar ForeignCar GoodCar BadCar
如果我们在http://www.oodesign.com/bridge-pattern.html查看桥模式的类图,它看起来像桥模式。但是,可以省略类层次结构CarAbstraction - CarAbstractionImpl。意味着CarAbstraction有一个CarImplementor和NativeCar&amp; ForeignCar将由CarAbstraction继承。
因此,从类图中看,它看起来像桥模式。
但概念点呢? NativeCar和ForeignCar是抽象还是可以用作实现?它们可以与GoodCar和BadCar交换吗?这个事实也需要考虑。如果NativeCar和ForeignCar是抽象的,他们将GoodCar和BadCar作为实现,那么这种情况的桥接模式。
答案 1 :(得分:0)
据我了解,你尝试做类似的事情:
When:
A
/ \
Aa Ab
/ \ / \
Aa1 Aa2 Ab1 Ab2
Refactor to:
A N
/ \ / \
Aa(N) Ab(N) 1 2
(来自这里:When do you use the Bridge Pattern? How is it different from Adapter pattern?)
我对Bridge Pattern的熟悉程度并不是很接近,但看起来不错。