策略模式(Strategy Pattern),定義了一系列的算法,將每一種算法封裝起來並能夠相互替換使用,策略模式讓算法獨立於使用它的客戶應用而獨立變化。java
OO設計原則:算法
面向接口編程(面向抽象編程)編程
封裝變化設計模式
多用組合,少用繼承ide
package com.main; //策略設計模式 public class StrategyPattern { public static void main(String[] args) { Duck trueDuck = new TrueDuck("真鴨子"); trueDuck.setSwim(new SwimImpl());// 設置游泳的具體實現 trueDuck.swim(); System.out.println("--------------"); Duck modelDuck = new ModelDuck("模型鴨子"); modelDuck.setSwim(new NotSwimImpl());// 設置游泳的具體實現 modelDuck.swim(); } } // 是否會游泳的接口(將游泳這一種能力抽象出來) interface Swimable { public void swim(); } // Swimable接口的實現類1 class SwimImpl implements Swimable { @Override public void swim() { System.out.println("會游泳"); } } // Swimable接口的實現類2 class NotSwimImpl implements Swimable { @Override public void swim() { System.out.println("不會游泳"); } } class Duck { private String name; // 只說明有游泳這個屬性,並不去肯定是否會游泳 private Swimable swim; public void setSwim(Swimable swim) { this.swim = swim; } public Duck(String name) { this.name = name; } public void swim() { System.out.print("我是" + name + ","); swim.swim(); } } // 真鴨子具體類 class TrueDuck extends Duck { public TrueDuck(String name) { super(name); } } // 模型鴨子具體類 class ModelDuck extends Duck { public ModelDuck(String name) { super(name); } }