0
我搜索了橋樑模式的例子,下面的例子很好地解釋了設計模式,但我對這個例子有一個問題。例如,如果手動齒輪handleGear方法對於汽車和卡車不同,我應該怎麼做,或者汽車齒輪手柄對於汽車或卡車齒輪的實現方式有所不同您能否爲這種情況提供示例代碼?橋樑模式按類型不同實施
/* Implementor interface*/
interface Gear{
void handleGear();
}
/* Concrete Implementor - 1 */
class ManualGear implements Gear{
public void handleGear(){
System.out.println("Manual gear");
}
}
/* Concrete Implementor - 2 */
class AutoGear implements Gear{
public void handleGear(){
System.out.println("Auto gear");
}
}
/* Abstraction (abstract class) */
abstract class Vehicle {
Gear gear;
public Vehicle(Gear gear){
this.gear = gear;
}
abstract void addGear();
}
/* RefinedAbstraction - 1*/
class Car extends Vehicle{
public Car(Gear gear){
super(gear);
// initialize various other Car components to make the car
}
public void addGear(){
System.out.print("Car handles ");
gear.handleGear();
}
}
/* RefinedAbstraction - 2 */
class Truck extends Vehicle{
public Truck(Gear gear){
super(gear);
// initialize various other Truck components to make the car
}
public void addGear(){
System.out.print("Truck handles ");
gear.handleGear();
}
}
/* Client program */
public class BridgeDemo {
public static void main(String args[]){
Gear gear = new ManualGear();
Vehicle vehicle = new Car(gear);
vehicle.addGear();
gear = new AutoGear();
vehicle = new Car(gear);
vehicle.addGear();
gear = new ManualGear();
vehicle = new Truck(gear);
vehicle.addGear();
gear = new AutoGear();
vehicle = new Truck(gear);
vehicle.addGear();
}
}
非常感謝。現在,我解決了橋樑模式試圖解決什麼樣的問題。文章約翰Sonmez關於我在這裏找到的橋樑模式https://simpleprogrammer.com/2015/06/08/design-patterns-simplified-the-bridge-pattern/解釋非常好的模式。 –