策略設計模式:
能夠根據所傳遞對象的不同而具有不同行爲的方法。
示列代碼:
package com.demo.gyw.java.design_pattern; /** * @Description: 策略模式 * @Author: gyw * @CreateDate: 2019/11/5 11:11 * @Version: 1.0 */ public class Strategy { /** * Strategy.strategic()方法接收一個Shape類型的引用作爲參數 * 這個引用可以是任何類型的Shape,如Circle、Square、Triangle * 根據所傳遞參數的不同,strategic方法有不同的行爲略 * * 示例:需要畫一個圖形Shape 可能是正方形Square/圓形Circle/三角形Triangle不同的形狀有不同的畫法 * @param entity */ public static void strategic(Shape entity){ // 接收策略引用的方法,S是策略引用 entity.outputShape(); // 方法中固有不變的部分 } public static void main(String[] args){ Shape sh = new Circle(); sh.outputShape(); // 新建圓圈Circle()對象作爲strategic()方法的參數,這裏的circle()對象就是一個策略,這裏用到了向上轉型(多態) strategic(new Circle()); // 策略正方形Square()對象 strategic(new Square()); // 策略三角形Triangle()對象 strategic(new Triangle()); } } /* * output: * this is a circle * this is a square * this is a triangle * */ /** * 基類,這裏可以是普通類,也可以是一個接口 */ abstract class Shape{ public abstract void outputShape(); } /** * 策略1 */ class Circle extends Shape{ @Override public void outputShape(){ System.out.println("this is a circle"); } } /** * 策略2 */ class Square extends Shape{ @Override public void outputShape(){ System.out.println("this is a square"); } } /** * 策略3 */ class Triangle extends Shape{ @Override public void outputShape(){ System.out.println("this is a triangle"); } }