1. 对象不在rep里
Dependecy 依赖
在方法参数或者局部变量中
class Duck
{
//no field to keep Flyable object
void fly(Flyable f)
{
f.fly();
}
}
2.对象在rep中
2.1 在rep中初始化:Composition 组合
class Duck {
Flyable f = new FlyWithWings();
void fly() {
f.fly();
}
}
2.2 在外部传参初始化:Aggregation 聚合
class Duck {
Flyable f;
void Duck(Flyable f) {
this.f = f;
}
void setFlyBehavior(f) {
this.f = f;
}
void fly() { f.fly();}
}
2.3 在rep中初始化,在构造其中传参可修改
class Duck {
Flyable f = new CannotFly();
void Duck(Flyable f) {
this.f = f;
}
void Duck() {
f = new FlyWithWings();
}
void fly() { f.fly(); }
}