Abstraction not tied to the Implementation: The abstraction interface (or abstract class with most of the behavior abstract) would not know/contain the implementation interface reference
Intent is to completely decouple the Abstraction from the Implementation
interface IAbstraction {
void behaviour1();
.....
}
interface IImplementation {
void behave1();
void behave2();
.....
}
class ConcreteAbstraction1 implements IAbstraction {
IImplementation implmentReference;
ConcreteAbstraction1() {
implmentReference = new ImplementationA() // Some implementation
}
void behaviour1() {
implmentReference.behave1();
}
.............
}
class ConcreteAbstraction2 implements IAbstraction {
IImplementation implmentReference;
ConcreteAbstraction1() {
implmentReference = new ImplementationB() // Some Other implementation
}
void behaviour1() {
implmentReference.behave2();
}
.............
}
当您希望在运行时插入算法或策略时,可以使用策略模式。作为范畴的模式也意味着它处理对象的行为。另一方面,桥梁是结构模式,处理对象的结构层次。它通过在抽象和实现之间引入一个精确的抽象来解耦抽象和实现。精确的抽象可能与运行时策略(在策略模式中)混淆。桥模式通过提供一种避免创建 n 个类的机制来处理结构方面的问题。
public class Ticket {
Date dateOfTravel;
int distance;
Vehicle vehicle;
Seat seat;
public float getTotalFare(){
//depends on
//Distance
//Vehicle - whether Vehicle is AC or non-AC.
//Seat - based on the location of the Seat.
//Fare = vehicleBaseFare*seatMultiplier*distance
}
}
在上述情况下,变化取决于父母(距离)以及子女(车辆和座位)。所以,这里的车辆和座位,都扮演桥梁。
给你
public class Vehicle {
TrackingDevice device;
public Coordinates getCoordinates(){
return device.getCoordinates();
}
}