面试题复习-常用设计模式-策略模式
策略接口:
package com.ajax.pattern.strategy; public interface EatWay { void cook(); }
策略1:
package com.ajax.pattern.strategy; public class Fry implements EatWay { @Override public void cook() { System.out.println("炸"); } }
策略2:
package com.ajax.pattern.strategy; public class Cook implements EatWay { @Override public void cook() { System.out.println("煮"); } }
环境:
package com.ajax.pattern.strategy; import lombok.AllArgsConstructor; @AllArgsConstructor public class Chicken { private EatWay eatWay; public void cook() { System.out.println("准备"); eatWay.cook(); } }
运行:
package com.ajax.pattern.strategy; public class Run { public static void main(String[] args) { Chicken chicken = new Chicken(new Fry()); chicken.cook(); } }