package cn.hnu.wy.strategy; public interface GoAlgorithm { public void go(); } package cn.hnu.wy.strategy; public class GoByDrivingAlgorithm implements GoAlgorithm { public void go() { System.out.println("Now I'm driving."); } } package cn.hnu.wy.strategy; public class GoByFlyingAlgorithm implements GoAlgorithm { public void go() { System.out.println("Now I'm flying."); } } package cn.hnu.wy.strategy; public class GoByFlyingFastAlgorithm implements GoAlgorithm { public void go() { System.out.println("Now I'm flying fast."); } } package cn.hnu.wy.strategy; public abstract class Vehicle { private GoAlgorithm goAlgorithm; public Vehicle() { } public void setGoAlgorithm (GoAlgorithm algorithm) { goAlgorithm = algorithm; } public void go() { goAlgorithm.go(); } } package cn.hnu.wy.strategy; public class Jet extends Vehicle { public Jet() { setGoAlgorithm(new GoByFlyingFastAlgorithm()); } } package cn.hnu.wy.strategy; public class RealJet { public static void main(String[] args) { Jet jet = new Jet(); jet.setGoAlgorithm(new GoByDrivingAlgorithm()); jet.go(); jet.setGoAlgorithm(new GoByFlyingFastAlgorithm()); jet.go(); jet.setGoAlgorithm(new GoByFlyingAlgorithm()); jet.go(); } } 运行结果: Now I'm driving.Now I'm flying fast.Now I'm flying.