将需要变化的那部分功能拿出来,
public interface RunBehavior { 跑抽象出一个接口 void run(); } public class RunNormally implements RunBehavior{ 正常跑 @Override public void run() { System.out.println("harding running..."); } } public class RunNoWay implements RunBehavior{ 不跑 @Override public void run() { } } public interface SayHiBehavior { 说 抽象出一个接口 void sayHi(); } public class SayHiNormally implements SayHiBehavior{ 正常说 @Override public void sayHi() { System.out.println("gegege"); } } public class SayHiScream implements SayHiBehavior{ 尖叫说 @Override public void sayHi() { System.out.println("gagagagaga...."); } } public abstract class Chicken { private SayHiBehavior sayHiBehavior; private RunBehavior runBehavior; public void setSayHiBehavior (SayHiBehavior sayHiBehavior) { this.sayHiBehavior=sayHiBehavior; } public void setRunBehavior(RunBehavior runBehavior){ this.runBehavior=runBehavior; } public void performSayHi(){ this.sayHiBehavior.sayHi(); } public void performRun(){ this.runBehavior.run(); } public abstract void show(); } public class WhiteChicken extends Chicken{ @Override public void show() { System.out.println("white..."); } } public class MyTest { public static void main(String[] args) { WhiteChicken whiteChicken=new WhiteChicken(); whiteChicken.setRunBehavior(new RunNormally()); whiteChicken.setSayHiBehavior(new SayHiNormally()); whiteChicken.performSayHi(); whiteChicken.performRun(); whiteChicken.show(); } }
参考: