{"id":200553,"date":"2020-09-20T09:59:42","date_gmt":"2020-09-20T01:59:42","guid":{"rendered":"https:\/\/gulass.cn\/?p=200553"},"modified":"2020-09-08T11:01:34","modified_gmt":"2020-09-08T03:01:34","slug":"strategy-pattern","status":"publish","type":"post","link":"https:\/\/gulass.cn\/strategy-pattern.html","title":{"rendered":"\u8bbe\u8ba1\u6a21\u5f0f\u4e4b\u7b56\u7565\u6a21\u5f0f"},"content":{"rendered":"
\u5bfc\u8bfb<\/td>\n | \u7b56\u7565\u6a21\u5f0f\uff08Strategy\uff09\uff1a\u5b83\u5b9a\u4e49\u4e86\u7b97\u6cd5\u5bb6\u65cf\uff0c\u5206\u522b\u5c01\u88c5\u8d77\u6765\uff0c\u8ba9\u5b83\u4eec\u4e4b\u95f4\u53ef\u4ee5\u4e92\u76f8\u66ff\u6362\uff0c\u6b64\u6a21\u5f0f\u8ba9\u7b97\u6cd5\u7684\u53d8\u5316\u4e0d\u4f1a\u5f71\u54cd\u5230\u4f7f\u7528\u7b97\u6cd5\u7684 Context\u3002<\/strong><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n \u7b56\u7565\u6a21\u5f0f\u662f\u4e00\u79cd\u5b9a\u4e49\u4e00\u7cfb\u5217\u7b97\u6cd5\u7684\u65b9\u6cd5\uff0c\u4ece\u6982\u5ff5\u4e0a\u6765\u770b\uff0c\u6240\u6709\u8fd9\u4e9b\u7b97\u6cd5\u5b8c\u5168\u7684\u90fd\u662f\u76f8\u540c\u7684\u5de5\u4f5c\uff0c\u53ea\u662f\u5b9e\u73b0\u4e0d\u540c\uff0c\u5b83\u53ef\u4ee5\u4ee5\u76f8\u540c\u7684\u65b9\u5f0f\u8c03\u7528\u6240\u6709\u7684\u7b97\u6cd5\uff0c\u51cf\u5c11\u4e86\u5404\u79cd\u7b97\u6cd5\u7c7b\u4e0e\u4f7f\u7528\u7c7b\u4e4b\u95f4\u7684\u8026\u5408\u3002<\/p>\n \u4f7f\u7528\u573a\u666f<\/strong><\/div>\n \u7b56\u7565\u6a21\u5f0f\u5c31\u662f\u7528\u6765\u5c01\u88c5\u7b97\u6cd5\u7684\uff0c\u4f46\u5728\u5b9e\u8df5\u4e2d\u4e5f\u53ef\u4ee5\u7528\u5b83\u6765\u5c01\u88c5\u51e0\u4e4e\u4efb\u4f55\u7c7b\u578b\u7684\u89c4\u5219\uff0c\u53ea\u8981\u5728\u5206\u6790\u8fc7\u7a0b\u4e2d\u542c\u5230\u9700\u8981\u5728\u4e0d\u540c\u65f6\u95f4\u5e94\u7528\u4e0d\u540c\u7684\u4e1a\u52a1\u89c4\u5219\uff0c\u5c31\u53ef\u4ee5\u8003\u8651\u4f7f\u7528\u7b56\u7565\u6a21\u5f0f\u5904\u7406\u8fd9\u79cd\u53d8\u5316\u7684\u53ef\u80fd\u6027\u3002<\/p>\n \u4f18\u70b9<\/strong><\/div>\n \u51cf\u5c11\u4e86\u5177\u4f53\u7684\u7b97\u6cd5\u548c\u4f7f\u7528\u7b97\u6cd5\u7c7b\u4e4b\u95f4\u7684\u8026\u5408 \u4e3e\u4f8b<\/strong><\/div>\n \r\npublic class Context\r\n{\r\n private readonly Strategy _strategy;\r\n\r\n public Context(Strategy strategy) => _strategy = strategy;\r\n\r\n public void Implement()\r\n {\r\n _strategy.AlgorithmImplement();\r\n }\r\n}\r\n\r\npublic abstract class Strategy\r\n{\r\n public abstract void AlgorithmImplement();\r\n}\r\n\r\npublic class ConcreteStrategyA : Strategy\r\n{\r\n public override void AlgorithmImplement()\r\n {\r\n Console.WriteLine(\"\u7b97\u6cd5A\u5b9e\u73b0\");\r\n }\r\n}\r\n\r\npublic class ConcreteStrategyB : Strategy\r\n{\r\n public override void AlgorithmImplement()\r\n {\r\n Console.WriteLine(\"\u7b97\u6cd5B\u5b9e\u73b0\");\r\n }\r\n}\r\n\r\npublic class ConcreteStrategyC : Strategy\r\n{\r\n public override void AlgorithmImplement()\r\n {\r\n Console.WriteLine(\"\u7b97\u6cd5C\u5b9e\u73b0\");\r\n }\r\n}\r\n<\/pre>\n |