用鸭子来举例
测试类
package com
.troila
.design_patterns
.strategy_pattern
;
public class TestDuck {
public static void main(String
[] args
) {
RedheadDuck redheadDuck
= new RedheadDuck();
redheadDuck
.isDuck();
redheadDuck
.swim();
redheadDuck
.display();
redheadDuck
.setFlyBehavior(new FlyWithWings());
redheadDuck
.setQuackBehavior(new Quack());
redheadDuck
.performFly();
redheadDuck
.performQuack();
}
}
抽象类
package com
.troila
.design_patterns
.strategy_pattern
;
public abstract class Duck {
private FlyBehavior flyBehavior
;
private QuackBehavior quackBehavior
;
public void setFlyBehavior(FlyBehavior f
) {
flyBehavior
= f
;
}
public void setQuackBehavior(QuackBehavior q
) {
quackBehavior
= q
;
}
public Boolean
isDuck() {
System
.out
.println("Duck.Class=====>我是一只鸭!");
return true;
}
public Boolean
swim() {
System
.out
.println("Duck.Class=====>鸭子游泳!");
return true;
}
public abstract Boolean
display();
public Boolean
performFly() {
flyBehavior
.fly();
return true;
}
public Boolean
performQuack() {
quackBehavior
.quack();
return true;
}
}
子类
package com
.troila
.design_patterns
.strategy_pattern
;
public class RedheadDuck extends Duck {
@Override
public Boolean
display() {
System
.out
.println("RedheadDuck.Class=====>我是红头鸭");
return true;
}
}
接口一
package com
.troila
.design_patterns
.strategy_pattern
;
public interface FlyBehavior {
void fly();
}
实现类
package com
.troila
.design_patterns
.strategy_pattern
;
public class FlyWithWings implements FlyBehavior{
@Override
public void fly() {
System
.out
.println("FlyWithWings.Class=====>我用翅膀飞");
}
}
package com
.troila
.design_patterns
.strategy_pattern
;
public class FlyNoWay implements FlyBehavior{
@Override
public void fly() {
System
.out
.println("FlyNoWay.Class=====>我根本不会飞");
}
}
接口二
package com
.troila
.design_patterns
.strategy_pattern
;
public interface QuackBehavior {
void quack();
}
实现类
package com
.troila
.design_patterns
.strategy_pattern
;
public class Quack implements QuackBehavior{
@Override
public void quack() {
System
.out
.println("Quack.Class=====>嘎嘎叫");
}
}
package com
.troila
.design_patterns
.strategy_pattern
;
public class Squeak implements QuackBehavior{
@Override
public void quack() {
System
.out
.println("Squeak.Class=====>吱吱叫");
}
}
package com
.troila
.design_patterns
.strategy_pattern
;
public class MuteQuack implements QuackBehavior{
@Override
public void quack() {
System
.out
.println("MuteQuack.Class=====>我不会叫");
}
}
转载请注明原文地址: https://lol.8miu.com/read-20750.html