├── .gitignore ├── .idea ├── description.html ├── encodings.xml ├── misc.xml ├── modules.xml ├── project-template.xml ├── uiDesigner.xml ├── vcs.xml └── workspace.xml ├── LICENSE ├── README.md ├── design-patterns.iml ├── document ├── adapter.jpg ├── chain_of_responsibility.jpg ├── command.jpg ├── composite.jpg ├── flyweight.jpg ├── state.jpg └── work_wechat_ewm.jpg └── src └── top └── ss007 ├── Main.java ├── adapter ├── AdapterClient.java ├── LogAdapter.java ├── LogFactory.java ├── NbLogger.java └── NbLoggerImp.java ├── bridge ├── BridgeClient.java ├── additives │ ├── ICoffeeAdditives.java │ ├── Milk.java │ └── Sugar.java └── volume │ ├── Coffee.java │ ├── LargeCoffee.java │ ├── RefinedCoffee.java │ └── SmallCoffee.java ├── builder ├── BuilderPatternService.java ├── simple │ └── PersonalComputer.java └── traditionversion │ ├── Computer.java │ ├── ComputerBuilder.java │ ├── ComputerDirector.java │ ├── LenovoComputerBuilder.java │ └── MacComputerBuilder.java ├── chainofresponsibility ├── BudgetHandler.java ├── CFO.java ├── DogWang2Cor.java ├── GroupLeader.java └── Manager.java ├── command ├── BingBingReceiver.java ├── Command.java ├── DogWang2Client.java ├── MiMiReceiver.java ├── PlayPianoCommand.java ├── RobotInvoker.java ├── SingSongCommand.java └── TiaoLaWuCommand.java ├── composite ├── AdminDepartment.java ├── CompositeClient.java ├── ItDepartment.java ├── OrganizationComponent.java └── OrganizationComposite.java ├── decorator ├── CoffeeDecorator.java ├── DecoratorClient.java ├── ICoffee.java ├── MilkDecorator.java ├── OriginalCoffee.java └── SugarDecorator.java ├── facade ├── DeliverySys.java ├── FacadeClient.java ├── OrderSys.java ├── PaymentSys.java └── ReportFacade.java ├── factory ├── Computer.java ├── FactoryPatternService.java ├── MacComputer.java ├── MiComputer.java ├── abstractfactory │ ├── AbstractFactory.java │ ├── AppleFactory.java │ ├── IPhone.java │ ├── MiPhone.java │ ├── MobilePhone.java │ └── XiaoMiFactory.java ├── factorymethod │ ├── ComputerFactory.java │ ├── MacComputerFactory.java │ └── MiComputerFactory.java └── simplefactory │ └── SimpleComputerFactory.java ├── flyweight ├── BlackChess.java ├── Chess.java ├── ChessFactory.java ├── Color.java ├── FlyweightClient.java └── WhiteChess.java ├── iterator ├── Class.java ├── IteratorClient.java └── Student.java ├── memento ├── GameCareTaker.java ├── GameOriginator.java ├── GameProgressMemento.java └── MementoClient.java ├── observer ├── Dog2WangObserver.java ├── GreenTeaBitchSubject.java ├── ObserverClient.java ├── ShangGuanSubject.java ├── TianDogObserver.java └── YinDangObserver.java ├── prototype ├── Prototype.java ├── PrototypeClient.java └── Report.java ├── proxy ├── ILawSuit.java ├── ProxyClient.java ├── dynamicproxy │ ├── CuiHuaNiu.java │ └── DynProxyLawyer.java └── statictproxy │ ├── DogWang2.java │ └── ProxyLawyer.java ├── run ├── DesignPatternName.java └── PatternExecutor.java ├── singleton ├── Singleton1.java ├── Singleton3.java ├── Singleton4.java ├── Singleton5.java ├── Singleton6.java └── SingletonClient.java ├── state ├── JdLogistics.java ├── LogisticsState.java ├── OrderState.java ├── ProductOutState.java ├── StateClient.java └── TransportState.java ├── strategy ├── ByBus.java ├── ByDiDiExpress.java ├── BySharedBicycle.java ├── CalculateStrategy.java ├── StrategyClient.java └── TransportFeeCalculator.java ├── template ├── JinShanLivePlay.java ├── LivePlay.java ├── TemplateClient.java └── TencentLivePlay.java └── visitor ├── BigHuYouCompany.java ├── CorporateSlave.java ├── CorporateSlaveVisitor.java ├── HumanSource.java ├── LiveApp.java ├── Programmer.java ├── SocialApp.java ├── Tester.java └── VisitorClient.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | .idea/workspace.xml 22 | 23 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 24 | hs_err_pid* 25 | /.idea/workspace.xml 26 | -------------------------------------------------------------------------------- /.idea/description.html: -------------------------------------------------------------------------------- 1 | Simple Java application that includes a class with main() method -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/project-template.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/workspace.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 18 | 19 | 20 | 23 | 24 | 25 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 63 | 64 | 73 | 74 | 80 | 81 | 89 | 90 | 91 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 1619229578533 112 | 139 | 140 | 1619428492449 141 | 146 | 147 | 1619428738770 148 | 153 | 154 | 1619886895774 155 | 160 | 161 | 1620022429295 162 | 167 | 168 | 1620029861577 169 | 174 | 175 | 1620029933053 176 | 181 | 182 | 1620115795105 183 | 188 | 189 | 1620116941508 190 | 195 | 196 | 1620123623231 197 | 202 | 203 | 1620124464765 204 | 209 | 210 | 1620202671980 211 | 216 | 217 | 1620233038325 218 | 223 | 224 | 1620742137101 225 | 230 | 231 | 1622340233705 232 | 237 | 238 | 1622340498350 239 | 244 | 245 | 1622475733576 246 | 251 | 252 | 1622887094333 253 | 258 | 259 | 1623079106513 260 | 265 | 266 | 1623492947300 267 | 272 | 273 | 1652113305733 274 | 279 | 280 | 1654355077341 281 | 286 | 287 | 1665807259693 288 | 293 | 294 | 1665808214001 295 | 300 | 303 | 304 | 306 | 307 | 316 | 318 | 319 | 337 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # design-patterns 2 | 3 | 致力于全网最说人话的设计模式讲解,使用最浅显的示例呈现设计模式的精髓,力争让每一位程序员都看得懂,入得门... 4 | 5 | ## 如何使用此源码 6 | 7 | 无任何三方依赖,可直接运行。运行后按照提示输入对应的设计模式名称,则会得到运行结果 8 | 9 | ``` 10 | 请输入列表中任意设计模式名称,列表:[COMMAND, CHAIN_OF_RESPONSIBILITY, BUILDER, ABSTRACT_FACTORY, FACTORY_METHOD, SIMPLE_FACTORY] 11 | 输入exit后按回车健可退出程序 12 | BUILDER 13 | assembled personal computer:Computer{cpu='I5处理器', ram='三星125', usbCount=2, keyboard='苹果键盘', display='苹果显示器'} 14 | mac computer:Computer{cpu='I5处理器', ram='三星125', usbCount=2, keyboard='苹果键盘', display='苹果显示器'} 15 | lenovo computer:Computer{cpu='I7处理器', ram='海力士222', usbCount=4, keyboard='联想键盘', display='联想显示器'} 16 | DD 17 | 输入错误,请重试。或者输入exit回车退出程序 18 | exit 19 | 20 | Process finished with exit code 0 21 | ``` 22 | 23 | 24 | # 概述 25 | 在IT这个行业,技术日新月异,可能你今年刚弄懂一个编程框架,明年它就不流行了。 然而即使在易变的IT世界也有很多几乎不变的知识,他们晦涩而重要,默默的将程序员划分为卓越与平庸两类。例如基础算法,设计模式等等。 26 | 27 | 首先,前辈们经过多年的摸索总结出了软件设计的六大原则,其可谓是面向对象设计之魂,其是设计模式的理论基础,所以强烈推荐在进入设计模式的世界之前,先读读这篇文章: 28 | 29 | [面向对象设计之魂(六大原则)](https://blog.shusheng007.top/archives/solid) 30 | 31 | 32 | # 定义 33 | 34 | 英文: 35 | >In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system. 36 | 37 | 汉语: 38 | >在软件工程领域,设计模式是一套通用的可复用的解决方案,用来解决在软件设计过程中产生的通用问题。它不是一个可以直接转换成源代码的设计,只是一套在软件系统设计过程中程序员应该遵循的最佳实践准则。 39 | 40 | 从定义可以看出,设计模式是一套语言无关的最佳设计实践准则,而不是什么真理定理,所以不可盲从。本文先期主要讲述GOF的面向对象的23种设计模式,由于本人惯用Java编程语言,所以代码示例均为Java实现。 41 | 42 | 43 | # 分类 44 | 45 | 46 | 设计模式按照其要解决的问题被分为3类: 47 | 48 | ## 创建型(creational) 49 | 50 | 顾名思义,主要解决如何灵活创建对象或者类的问题,共**5**个。 51 | 1. 工厂方法模式(Factory Method) 52 | 53 | [秒懂设计模式之工厂方法模式(Factory Method Pattern)]( https://blog.shusheng007.top/archives/factory-method-pattern) 54 | 55 | 2. 抽象工厂模式(Abstract Factory) 56 | 57 | [秒懂设计模式之抽象工厂模式(Abstract Factory Pattern)]( https://blog.shusheng007.top/archives/abstract-factory-pattern) 58 | 59 | 60 | 3. 构建者模式(Builder) 61 | 62 | [秒懂设计模式之建造者模式(Builder pattern)](https://blog.shusheng007.top/archives/builder-pattern) 63 | 64 | 4. 单例模式(Singleton) 65 | 66 | [秒懂设计模式之单例模式(Singleton Pattern)]( https://blog.shusheng007.top/archives/singleton-pattern) 67 | 68 | 5. 原型模式(Prototype) 69 | 70 | [秒懂设计模式之原型模式(Prototype Pattern)](https://blog.shusheng007.top/archives/prototype-pattern) 71 | 72 | 73 | 另外还有一个简单工厂模式,其虽然不在GOF23种设计模式之中,但是应用也很广泛: 74 | 75 | [秒懂设计模式之简单工厂模式(Simple Factory Pattern)](https://blog.shusheng007.top/archives/simple-factory-pattern) 76 | 77 | 78 | 79 | ## 结构型(structural) 80 | 81 | 结构型设计模式主要用于将类或对象进行组合从而构建灵活而高效的结构,共**7**个。 82 | 83 | 1. 适配器模式(Adapter) 84 | 85 | [秒懂设计模式之适配器模式(Adapter Pattern)](https://blog.shusheng007.top/archives/adapter-pattern) 86 | 87 | 2. 桥接模式(Bridge) 88 | 89 | [秒懂设计模式之桥接模式(Bridge Pattern)](https://blog.shusheng007.top/archives/bridge-pattern) 90 | 91 | 3. 组合模式(Composite) 92 | 93 | [秒懂设计模式之组合模式(Composite Pattern)](https://blog.shusheng007.top/archives/composite-pattern) 94 | 95 | 4. 装饰者模式(Decorator) 96 | 97 | [秒懂设计模式之装饰者模式(Decorator Pattern)](https://blog.shusheng007.top/archives/decorator-pattern) 98 | 99 | 5. 外观模式(Facade) 100 | 101 | [秒懂设计模式之外观模式(Facade Pattern)](https://blog.shusheng007.top/archives/facade-pattern) 102 | 103 | 6. 享元模式(Flyweight) 104 | 105 | [秒懂设计模式之享元模式(Flyweight Pattern)](https://blog.shusheng007.top/archives/flyweight-pattern) 106 | 107 | 7. 代理模式(Proxy) 108 | 109 | [秒懂Java代理与动态代理模式(Proxy Pattern)](https://blog.shusheng007.top/archives/proxy-pattern) 110 | 111 | ## 行为型(behavioral) 112 | 113 | 行为型设计模式主要解决类或者对象之间互相通信的问题,共**11**个 114 | 115 | 1. 责任链模式(Chain of responsibility) 116 | 117 | [秒懂设计模式之责任链模式(Chain of responsibility)](https://blog.shusheng007.top/archives/chain-of-responsibility-pattern) 118 | 119 | 2. 命令模式(Command) 120 | 121 | [秒懂设计模式之命令模式(Command Pattern)](https://blog.shusheng007.top/archives/command-pattern) 122 | 123 | 3. 解释器模式(Interpreter) 124 | 125 | 敬请期待 126 | 127 | 4. 迭代器模式(Iterator) 128 | 129 | [秒懂设计模式之迭代器模式(Iterator Pattern)](https://blog.shusheng007.top/archives/iterator-pattern) 130 | 131 | 5. 中介者模式(Mediator) 132 | 133 | 敬请期待 134 | 135 | 6. 备忘录模式(Memento) 136 | 137 | [秒懂设计模式之备忘录模式(Memento Pattern)](https://blog.shusheng007.top/archives/memento-pattern) 138 | 139 | 7. 观察者模式(Observer) 140 | 141 | [秒懂设计模式之观察者模式(Observer Pattern)](https://blog.shusheng007.top/archives/observer-pattern) 142 | 143 | 8. 策略模式(Strategy) 144 | 145 | [秒懂设计模式之策略模式(Strategy Pattern)](https://blog.shusheng007.top/archives/strategy-pattern) 146 | 147 | 9. 状态模式(State) 148 | 149 | [秒懂设计模式之状态模式(State Pattern)](https://blog.shusheng007.top/archives/state-pattern) 150 | 151 | 10. 模板方法模式(Template method) 152 | 153 | [秒懂设计模式之模板方法模式(Template Method Pattern)](https://blog.shusheng007.top/archives/template-method-pattern) 154 | 155 | 11. 访问者模式(Visitor) 156 | 157 | [秒懂设计模式之访问者模式(Visitor Pattern)](https://blog.shusheng007.top/archives/visitor-pattern) 158 | 159 | # 总结 160 | 本篇为设计模式汇总篇,我会不断的完善其中没有实例的设计模式,你可以先点赞收藏起来,那样就再也不怕找不到走向卓越的路了。最后请抬起你的小手手随手点个小星星... 161 | 162 | 163 | # 联系 164 | 165 | 你可以从下面找到我,希望我们可以成为兴趣相投的好朋友: 166 | 167 | - 个人博客:[ShuSheng007个人博客](https://blog.shusheng007.top) 168 | - CSDN博客:[ShuSheng007CSDN博客](https://blog.csdn.net/ShuSheng0007) 169 | - 微信: 170 | -------------------------------------------------------------------------------- /design-patterns.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /document/adapter.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shusheng007/design-patterns/7c3e09bf8f2efcd07f1912b3d38ba21d2d7bbb63/document/adapter.jpg -------------------------------------------------------------------------------- /document/chain_of_responsibility.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shusheng007/design-patterns/7c3e09bf8f2efcd07f1912b3d38ba21d2d7bbb63/document/chain_of_responsibility.jpg -------------------------------------------------------------------------------- /document/command.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shusheng007/design-patterns/7c3e09bf8f2efcd07f1912b3d38ba21d2d7bbb63/document/command.jpg -------------------------------------------------------------------------------- /document/composite.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shusheng007/design-patterns/7c3e09bf8f2efcd07f1912b3d38ba21d2d7bbb63/document/composite.jpg -------------------------------------------------------------------------------- /document/flyweight.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shusheng007/design-patterns/7c3e09bf8f2efcd07f1912b3d38ba21d2d7bbb63/document/flyweight.jpg -------------------------------------------------------------------------------- /document/state.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shusheng007/design-patterns/7c3e09bf8f2efcd07f1912b3d38ba21d2d7bbb63/document/state.jpg -------------------------------------------------------------------------------- /document/work_wechat_ewm.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shusheng007/design-patterns/7c3e09bf8f2efcd07f1912b3d38ba21d2d7bbb63/document/work_wechat_ewm.jpg -------------------------------------------------------------------------------- /src/top/ss007/Main.java: -------------------------------------------------------------------------------- 1 | package top.ss007; 2 | 3 | import top.ss007.run.DesignPatternName; 4 | import top.ss007.run.PatternExecutor; 5 | 6 | import java.util.Scanner; 7 | 8 | public class Main { 9 | 10 | public static void main(String[] args) { 11 | Scanner scanner = new Scanner(System.in); 12 | System.out.println(String.format("请输入列表中任意设计模式名称,列表:%s", DesignPatternName.patterList())); 13 | System.out.println("输入exit后按回车健可退出程序"); 14 | PatternExecutor executor = new PatternExecutor(); 15 | while (true) { 16 | final String input = scanner.nextLine(); 17 | if ("exit".equalsIgnoreCase(input)) { 18 | break; 19 | } 20 | try { 21 | executor.run(input); 22 | } catch (IllegalArgumentException e) { 23 | System.out.println("输入错误,请重试。或者输入exit回车退出程序"); 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/top/ss007/adapter/AdapterClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.adapter; 2 | 3 | /** 4 | * Created by Ben.Wang 5 | *

6 | * author : Ben.Wang 7 | * date : 2021/4/25 11:35 8 | * description: 9 | */ 10 | public class AdapterClient { 11 | public void recordLog() { 12 | LogFactory logFactory = new LogAdapter(new NbLoggerImp()); 13 | logFactory.debug("Test", "我将使用牛逼logger打印log"); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/top/ss007/adapter/LogAdapter.java: -------------------------------------------------------------------------------- 1 | package top.ss007.adapter; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * Created by Ben.Wang 7 | *

8 | * author : Ben.Wang 9 | * date : 2021/4/25 11:30 10 | * description: 11 | */ 12 | public class LogAdapter implements LogFactory { 13 | private NbLogger nbLogger; 14 | 15 | public LogAdapter(NbLogger nbLogger) { 16 | this.nbLogger = nbLogger; 17 | } 18 | 19 | @Override 20 | public void debug(String tag, String message) { 21 | Objects.requireNonNull(nbLogger); 22 | nbLogger.d(1, message); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/top/ss007/adapter/LogFactory.java: -------------------------------------------------------------------------------- 1 | package top.ss007.adapter; 2 | 3 | /** 4 | * Created by Ben.Wang 5 | *

6 | * author : Ben.Wang 7 | * date : 2021/4/25 11:24 8 | * description: 9 | */ 10 | public interface LogFactory { 11 | void debug(String tag,String message); 12 | } 13 | -------------------------------------------------------------------------------- /src/top/ss007/adapter/NbLogger.java: -------------------------------------------------------------------------------- 1 | package top.ss007.adapter; 2 | 3 | /** 4 | * Created by Ben.Wang 5 | *

6 | * author : Ben.Wang 7 | * date : 2021/4/25 11:26 8 | * description: 9 | */ 10 | public interface NbLogger { 11 | void d(int priority, String message, Object ... obj); 12 | } 13 | -------------------------------------------------------------------------------- /src/top/ss007/adapter/NbLoggerImp.java: -------------------------------------------------------------------------------- 1 | package top.ss007.adapter; 2 | 3 | /** 4 | * Created by Ben.Wang 5 | *

6 | * author : Ben.Wang 7 | * date : 2021/4/25 11:27 8 | * description: 9 | */ 10 | public class NbLoggerImp implements NbLogger { 11 | @Override 12 | public void d(int priority, String message, Object... obj) { 13 | System.out.println(String.format("牛逼logger记录:%s",message)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/top/ss007/bridge/BridgeClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.bridge; 2 | 3 | import top.ss007.bridge.additives.Milk; 4 | import top.ss007.bridge.additives.Sugar; 5 | import top.ss007.bridge.volume.LargeCoffee; 6 | import top.ss007.bridge.volume.RefinedCoffee; 7 | import top.ss007.bridge.volume.SmallCoffee; 8 | 9 | /** 10 | * Copyright (C) 2021 ShuSheng007 11 | * 完全享有此软件的著作权 12 | * 13 | * @author ShuSheng007 14 | * @time 2021/5/1 16:50 15 | * @description 16 | */ 17 | public class BridgeClient { 18 | 19 | public void orderOffer() { 20 | 21 | //两杯加奶的大杯咖啡 22 | RefinedCoffee largeWithMilk = new LargeCoffee(new Milk()); 23 | largeWithMilk.orderCoffee(2); 24 | largeWithMilk.checkQuality(); 25 | System.out.println("-----------------------------------------"); 26 | //两杯加奶的大杯咖啡 27 | RefinedCoffee smallWithSugar = new SmallCoffee(new Sugar()); 28 | smallWithSugar.orderCoffee(1); 29 | smallWithSugar.checkQuality(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/top/ss007/bridge/additives/ICoffeeAdditives.java: -------------------------------------------------------------------------------- 1 | package top.ss007.bridge.additives; 2 | 3 | public interface ICoffeeAdditives { 4 | void addSomething(); 5 | } 6 | -------------------------------------------------------------------------------- /src/top/ss007/bridge/additives/Milk.java: -------------------------------------------------------------------------------- 1 | package top.ss007.bridge.additives; 2 | 3 | public class Milk implements ICoffeeAdditives { 4 | @Override 5 | public void addSomething() { 6 | System.out.println("加奶"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/top/ss007/bridge/additives/Sugar.java: -------------------------------------------------------------------------------- 1 | package top.ss007.bridge.additives; 2 | 3 | public class Sugar implements ICoffeeAdditives { 4 | @Override 5 | public void addSomething() { 6 | System.out.println("加糖"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/top/ss007/bridge/volume/Coffee.java: -------------------------------------------------------------------------------- 1 | package top.ss007.bridge.volume; 2 | 3 | import top.ss007.bridge.additives.ICoffeeAdditives; 4 | 5 | public abstract class Coffee { 6 | protected ICoffeeAdditives additives; 7 | 8 | public Coffee(ICoffeeAdditives additives) { 9 | this.additives = additives; 10 | } 11 | 12 | public abstract void orderCoffee(int count); 13 | } 14 | -------------------------------------------------------------------------------- /src/top/ss007/bridge/volume/LargeCoffee.java: -------------------------------------------------------------------------------- 1 | package top.ss007.bridge.volume; 2 | 3 | import top.ss007.bridge.additives.ICoffeeAdditives; 4 | 5 | /** 6 | * Copyright (C) 2021 ShuSheng007 7 | * 完全享有此软件的著作权 8 | * 9 | * @author ShuSheng007 10 | * @time 2021/5/1 16:47 11 | * @description 12 | */ 13 | public class LargeCoffee extends RefinedCoffee { 14 | public LargeCoffee(ICoffeeAdditives additives) { 15 | super(additives); 16 | } 17 | 18 | @Override 19 | public void orderCoffee(int count) { 20 | additives.addSomething(); 21 | System.out.println(String.format("大杯咖啡%d杯",count)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/top/ss007/bridge/volume/RefinedCoffee.java: -------------------------------------------------------------------------------- 1 | package top.ss007.bridge.volume; 2 | 3 | import top.ss007.bridge.additives.ICoffeeAdditives; 4 | 5 | import java.util.Random; 6 | 7 | public abstract class RefinedCoffee extends Coffee { 8 | public RefinedCoffee(ICoffeeAdditives additives) { 9 | super(additives); 10 | } 11 | 12 | public void checkQuality() { 13 | Random ran = new Random(); 14 | System.out.println(String.format("%s 添加%s", additives.getClass().getSimpleName(), ran.nextBoolean() ? "太多" : "正常")); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/top/ss007/bridge/volume/SmallCoffee.java: -------------------------------------------------------------------------------- 1 | package top.ss007.bridge.volume; 2 | 3 | import top.ss007.bridge.additives.ICoffeeAdditives; 4 | 5 | /** 6 | * Copyright (C) 2021 ShuSheng007 7 | * 完全享有此软件的著作权 8 | * 9 | * @author ShuSheng007 10 | * @time 2021/5/1 16:49 11 | * @description 12 | */ 13 | public class SmallCoffee extends RefinedCoffee { 14 | public SmallCoffee(ICoffeeAdditives additives) { 15 | super(additives); 16 | } 17 | 18 | @Override 19 | public void orderCoffee(int count) { 20 | additives.addSomething(); 21 | System.out.println(String.format("小杯咖啡%d杯",count)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/top/ss007/builder/BuilderPatternService.java: -------------------------------------------------------------------------------- 1 | package top.ss007.builder; 2 | 3 | 4 | import top.ss007.builder.simple.PersonalComputer; 5 | import top.ss007.builder.traditionversion.*; 6 | 7 | public class BuilderPatternService { 8 | 9 | 10 | public void assemblePcUseSimpleBuilder() { 11 | PersonalComputer computer = new PersonalComputer.Builder("I5处理器", "三星125") 12 | .setDisplay("苹果显示器") 13 | .setKeyboard("苹果键盘") 14 | .setUsbCount(2) 15 | .build(); 16 | System.out.println("assembled personal computer:" + computer.toString()); 17 | } 18 | 19 | public void assemblePcUseTraditionBuilder() { 20 | //指导创建步骤 21 | ComputerDirector director = new ComputerDirector(); 22 | 23 | ComputerBuilder builder = new MacComputerBuilder("I5处理器", "三星125"); 24 | director.makeComputer(builder); 25 | Computer macComputer = builder.getComputer(); 26 | System.out.println("mac computer:" + macComputer.toString()); 27 | 28 | ComputerBuilder lenovoBuilder = new LenovoComputerBuilder("I7处理器", "海力士222"); 29 | director.makeComputer(lenovoBuilder); 30 | Computer lenovoComputer = lenovoBuilder.getComputer(); 31 | System.out.println("lenovo computer:" + lenovoComputer.toString()); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/top/ss007/builder/simple/PersonalComputer.java: -------------------------------------------------------------------------------- 1 | package top.ss007.builder.simple; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/24. 5 | */ 6 | public class PersonalComputer { 7 | private final String cpu;//必须 8 | private final String ram;//必须 9 | private final int usbCount;//可选 10 | private final String keyboard;//可选 11 | private final String display;//可选 12 | 13 | private PersonalComputer(Builder builder) { 14 | this.cpu = builder.cpu; 15 | this.ram = builder.ram; 16 | this.usbCount = builder.usbCount; 17 | this.keyboard = builder.keyboard; 18 | this.display = builder.display; 19 | } 20 | 21 | public String getCpu() { 22 | return cpu; 23 | } 24 | 25 | public String getRam() { 26 | return ram; 27 | } 28 | 29 | public int getUsbCount() { 30 | return usbCount; 31 | } 32 | 33 | public String getKeyboard() { 34 | return keyboard; 35 | } 36 | 37 | public String getDisplay() { 38 | return display; 39 | } 40 | 41 | public static class Builder { 42 | private String cpu;//必须 43 | private String ram;//必须 44 | private int usbCount;//可选 45 | private String keyboard;//可选 46 | private String display;//可选 47 | 48 | public Builder(String cup, String ram) { 49 | this.cpu = cup; 50 | this.ram = ram; 51 | } 52 | 53 | public Builder setUsbCount(int usbCount) { 54 | this.usbCount = usbCount; 55 | return this; 56 | } 57 | 58 | public Builder setKeyboard(String keyboard) { 59 | this.keyboard = keyboard; 60 | return this; 61 | } 62 | 63 | public Builder setDisplay(String display) { 64 | this.display = display; 65 | return this; 66 | } 67 | 68 | public PersonalComputer build() { 69 | return new PersonalComputer(this); 70 | } 71 | } 72 | 73 | @Override 74 | public String toString() { 75 | return "Computer{" + 76 | "cpu='" + cpu + '\'' + 77 | ", ram='" + ram + '\'' + 78 | ", usbCount=" + usbCount + 79 | ", keyboard='" + keyboard + '\'' + 80 | ", display='" + display + '\'' + 81 | '}'; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/top/ss007/builder/traditionversion/Computer.java: -------------------------------------------------------------------------------- 1 | package top.ss007.builder.traditionversion; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/24. 5 | */ 6 | public class Computer { 7 | private String cpu;//必须 8 | private String ram;//必须 9 | private int usbCount;//可选 10 | private String keyboard;//可选 11 | private String display;//可选 12 | 13 | public Computer(String cpu, String ram) { 14 | this.cpu = cpu; 15 | this.ram = ram; 16 | } 17 | 18 | public void setUsbCount(int usbCount) { 19 | this.usbCount = usbCount; 20 | } 21 | 22 | public void setKeyboard(String keyboard) { 23 | this.keyboard = keyboard; 24 | } 25 | 26 | public void setDisplay(String display) { 27 | this.display = display; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return "Computer{" + 33 | "cpu='" + cpu + '\'' + 34 | ", ram='" + ram + '\'' + 35 | ", usbCount=" + usbCount + 36 | ", keyboard='" + keyboard + '\'' + 37 | ", display='" + display + '\'' + 38 | '}'; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/top/ss007/builder/traditionversion/ComputerBuilder.java: -------------------------------------------------------------------------------- 1 | package top.ss007.builder.traditionversion; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/24. 5 | */ 6 | public abstract class ComputerBuilder { 7 | public abstract void setUsbCount(); 8 | public abstract void setKeyboard(); 9 | public abstract void setDisplay(); 10 | 11 | public abstract Computer getComputer(); 12 | } 13 | -------------------------------------------------------------------------------- /src/top/ss007/builder/traditionversion/ComputerDirector.java: -------------------------------------------------------------------------------- 1 | package top.ss007.builder.traditionversion; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/24. 5 | */ 6 | public class ComputerDirector { 7 | public void makeComputer(ComputerBuilder builder) { 8 | builder.setUsbCount(); 9 | builder.setDisplay(); 10 | builder.setKeyboard(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/top/ss007/builder/traditionversion/LenovoComputerBuilder.java: -------------------------------------------------------------------------------- 1 | package top.ss007.builder.traditionversion; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/24. 5 | */ 6 | public class LenovoComputerBuilder extends ComputerBuilder { 7 | 8 | private Computer computer; 9 | 10 | public LenovoComputerBuilder(String cpu, String ram) { 11 | computer=new Computer(cpu,ram); 12 | } 13 | 14 | 15 | @Override 16 | public void setUsbCount() { 17 | computer.setUsbCount(4); 18 | } 19 | 20 | @Override 21 | public void setKeyboard() { 22 | computer.setKeyboard("联想键盘"); 23 | } 24 | 25 | @Override 26 | public void setDisplay() { 27 | computer.setDisplay("联想显示器"); 28 | } 29 | 30 | @Override 31 | public Computer getComputer() { 32 | return computer; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/top/ss007/builder/traditionversion/MacComputerBuilder.java: -------------------------------------------------------------------------------- 1 | package top.ss007.builder.traditionversion; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/24. 5 | */ 6 | public class MacComputerBuilder extends ComputerBuilder { 7 | 8 | private Computer computer; 9 | 10 | public MacComputerBuilder(String cpu, String ram) { 11 | computer = new Computer(cpu, ram); 12 | } 13 | 14 | 15 | @Override 16 | public void setUsbCount() { 17 | computer.setUsbCount(2); 18 | } 19 | 20 | @Override 21 | public void setKeyboard() { 22 | computer.setKeyboard("苹果键盘"); 23 | } 24 | 25 | @Override 26 | public void setDisplay() { 27 | computer.setDisplay("苹果显示器"); 28 | } 29 | 30 | @Override 31 | public Computer getComputer() { 32 | return computer; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/top/ss007/chainofresponsibility/BudgetHandler.java: -------------------------------------------------------------------------------- 1 | package top.ss007.chainofresponsibility; 2 | 3 | /** 4 | * Created by Ben.Wang 5 | *

6 | * author : Ben.Wang 7 | * date : 2021/4/23 13:15 8 | * description: 9 | */ 10 | public interface BudgetHandler { 11 | void setNextHandler(BudgetHandler nextHandler); 12 | 13 | boolean handle(int amount); 14 | } 15 | -------------------------------------------------------------------------------- /src/top/ss007/chainofresponsibility/CFO.java: -------------------------------------------------------------------------------- 1 | package top.ss007.chainofresponsibility; 2 | 3 | /** 4 | * Created by Ben.Wang 5 | *

6 | * author : Ben.Wang 7 | * date : 2021/4/23 13:30 8 | * description: 9 | */ 10 | public class CFO implements BudgetHandler { 11 | private BudgetHandler nextHandler; 12 | 13 | @Override 14 | public void setNextHandler(BudgetHandler nextHandler) { 15 | this.nextHandler = nextHandler; 16 | } 17 | 18 | @Override 19 | public boolean handle(int amount) { 20 | if(amount<50000){ 21 | System.out.println("CFO同意,希望你再接再厉,为公司做出更大的贡献。"); 22 | return true; 23 | } 24 | if (nextHandler!=null){ 25 | return nextHandler.handle(amount); 26 | } 27 | //已经没有更高级的管理层来处理了 28 | System.out.println(String.format("%d太多了,回去好好看看能不能缩减一下",amount)); 29 | return false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/top/ss007/chainofresponsibility/DogWang2Cor.java: -------------------------------------------------------------------------------- 1 | package top.ss007.chainofresponsibility; 2 | 3 | /** 4 | * Created by Ben.Wang 5 | *

6 | * author : Ben.Wang 7 | * date : 2021/4/23 13:54 8 | * description: 9 | */ 10 | public class DogWang2Cor { 11 | 12 | public void applyBudget() { 13 | GroupLeader leader = new GroupLeader(); 14 | Manager manager = new Manager(); 15 | CFO cfo = new CFO(); 16 | 17 | leader.setNextHandler(manager); 18 | manager.setNextHandler(cfo); 19 | 20 | System.out.println(String.format("领导您好:由于开发需求,需要购买一台Mac笔记本电脑,预算为%d 望领导批准", 20000)); 21 | if (leader.handle(20000)) { 22 | System.out.println("谢谢领导"); 23 | } else { 24 | System.out.println("巧妇难为无米之炊,只能划船了..."); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/top/ss007/chainofresponsibility/GroupLeader.java: -------------------------------------------------------------------------------- 1 | package top.ss007.chainofresponsibility; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * Created by Ben.Wang 7 | *

8 | * author : Ben.Wang 9 | * date : 2021/4/23 13:30 10 | * description: 11 | */ 12 | public class GroupLeader implements BudgetHandler { 13 | private BudgetHandler nextHandler; 14 | 15 | @Override 16 | public void setNextHandler(BudgetHandler nextHandler) { 17 | this.nextHandler = nextHandler; 18 | } 19 | 20 | @Override 21 | public boolean handle(int amount) { 22 | Objects.requireNonNull(nextHandler); 23 | if(amount<1000){ 24 | System.out.println("小钱,批了!"); 25 | return true; 26 | } 27 | System.out.println(String.format("%d超出GroupLeader权限,请更高级管理层批复",amount)); 28 | return nextHandler.handle(amount); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/top/ss007/chainofresponsibility/Manager.java: -------------------------------------------------------------------------------- 1 | package top.ss007.chainofresponsibility; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * Created by Ben.Wang 7 | *

8 | * author : Ben.Wang 9 | * date : 2021/4/23 13:30 10 | * description: 11 | */ 12 | public class Manager implements BudgetHandler { 13 | private BudgetHandler nextHandler; 14 | 15 | @Override 16 | public void setNextHandler(BudgetHandler nextHandler) { 17 | this.nextHandler = nextHandler; 18 | } 19 | 20 | @Override 21 | public boolean handle(int amount) { 22 | Objects.requireNonNull(nextHandler); 23 | if(amount<5000){ 24 | System.out.println("小于2000块,我这个经理可以决定:同意!"); 25 | return true; 26 | } 27 | System.out.println(String.format("%d超出Manager权限,请更高级管理层批复",amount)); 28 | return nextHandler.handle(amount); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/top/ss007/command/BingBingReceiver.java: -------------------------------------------------------------------------------- 1 | package top.ss007.command; 2 | 3 | /** 4 | * 具体命令执行者,这就是个具体的业务类。 5 | */ 6 | public class BingBingReceiver { 7 | 8 | public void singSong(){ 9 | System.out.println("落花满天蔽月光 借一杯附荐凤台上..."); 10 | } 11 | 12 | public void playPiano(){ 13 | System.out.println("随着BingBing纤细的双手在琴弦上来回撩拨,美妙的音乐响彻了整个房间..."); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/top/ss007/command/Command.java: -------------------------------------------------------------------------------- 1 | package top.ss007.command; 2 | 3 | /** 4 | * 命令接口,所有具体的命令都会实现此接口,Invoker只认识此接口 5 | * 6 | * 其实现类自己包含了可以执行自己的对象(receiver),已经执行时候需要的数据 7 | */ 8 | public interface Command { 9 | void execute(); 10 | } 11 | -------------------------------------------------------------------------------- /src/top/ss007/command/DogWang2Client.java: -------------------------------------------------------------------------------- 1 | package top.ss007.command; 2 | 3 | /** 4 | * 客户端,客户端负责构建命令并使用Invoker执行 5 | */ 6 | public class DogWang2Client { 7 | 8 | //享受陪伴机器人的服务 9 | public void enjoySexRobot() { 10 | //robot 控制系统,用户通过此系统来发出命令 11 | RobotInvoker invoker = new RobotInvoker(); 12 | 13 | //生成唱歌弹琴命令 14 | BingBingReceiver bingBingReceiver = new BingBingReceiver(); 15 | SingSongCommand singSongCommand = new SingSongCommand(bingBingReceiver); 16 | PlayPianoCommand playPianoCommand = new PlayPianoCommand(bingBingReceiver); 17 | //构建执行计划 18 | invoker.addCommands(singSongCommand); 19 | invoker.addCommands(playPianoCommand); 20 | //执行命令 21 | invoker.executeCommand(); 22 | 23 | //生成跳舞命令 24 | MiMiReceiver miMiReceiver = new MiMiReceiver(); 25 | TiaoLaWuCommand tiaoLaWuCommand = new TiaoLaWuCommand(miMiReceiver, "半小时"); 26 | //构建执行计划 27 | invoker.clearCommand(); 28 | invoker.addCommands(tiaoLaWuCommand); 29 | 30 | //执行命令 31 | invoker.executeCommand(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/top/ss007/command/MiMiReceiver.java: -------------------------------------------------------------------------------- 1 | package top.ss007.command; 2 | 3 | /** 4 | * 命令执行者 5 | */ 6 | public class MiMiReceiver { 7 | public void hotDance(){ 8 | System.out.println("终日以文雅示人的大MIMI尽然也有她狂野的一面,只见她随着音乐疯狂的扭动,魅惑的表情更是让人想入非非,欲罢不能..."); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/top/ss007/command/PlayPianoCommand.java: -------------------------------------------------------------------------------- 1 | package top.ss007.command; 2 | 3 | public class PlayPianoCommand implements Command { 4 | private BingBingReceiver bingBing; 5 | 6 | public PlayPianoCommand(BingBingReceiver bingBing) { 7 | this.bingBing = bingBing; 8 | } 9 | 10 | @Override 11 | public void execute() { 12 | bingBing.playPiano(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/top/ss007/command/RobotInvoker.java: -------------------------------------------------------------------------------- 1 | package top.ss007.command; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | 7 | /** 8 | * 调用者,其只认识Command接口,而不认识具体的实现。 9 | * 其负责按照客户端的指令设置并执行命令,像命令的撤销,日志的记录等功能都要在此类中完成 10 | */ 11 | public class RobotInvoker { 12 | private final List sexRobotCommands = new ArrayList<>(); 13 | 14 | public void clearCommand(){ 15 | sexRobotCommands.clear(); 16 | } 17 | 18 | //设置一套命令,不知道具体执行者是谁 19 | public void addCommands(Command command) { 20 | sexRobotCommands.add(command); 21 | } 22 | 23 | //执行系列命令 24 | public void executeCommand() { 25 | for (Command command : sexRobotCommands) { 26 | command.execute(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/top/ss007/command/SingSongCommand.java: -------------------------------------------------------------------------------- 1 | package top.ss007.command; 2 | 3 | public class SingSongCommand implements Command { 4 | private BingBingReceiver bingBing; 5 | 6 | public SingSongCommand(BingBingReceiver bingBing) { 7 | this.bingBing = bingBing; 8 | } 9 | 10 | @Override 11 | public void execute() { 12 | bingBing.singSong(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/top/ss007/command/TiaoLaWuCommand.java: -------------------------------------------------------------------------------- 1 | package top.ss007.command; 2 | 3 | public class TiaoLaWuCommand implements Command { 4 | private MiMiReceiver daMiMi; 5 | private String duration;//跳舞的时长 6 | 7 | public TiaoLaWuCommand(MiMiReceiver daMiMi, String duration) { 8 | this.daMiMi = daMiMi; 9 | this.duration = duration; 10 | } 11 | 12 | @Override 13 | public void execute() { 14 | System.out.println(String.format("开始跳舞表演,时长为:%s", duration)); 15 | daMiMi.hotDance(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/top/ss007/composite/AdminDepartment.java: -------------------------------------------------------------------------------- 1 | package top.ss007.composite; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/3 15:09 9 | * @description 10 | */ 11 | public class AdminDepartment extends OrganizationComponent { 12 | 13 | public AdminDepartment(String name) { 14 | super(name); 15 | } 16 | 17 | @Override 18 | public int getStaffCount() { 19 | return 50; 20 | } 21 | 22 | @Override 23 | public void add(OrganizationComponent organization) { 24 | throw new UnsupportedOperationException(this.getName()+"已经是最基本部门,无法增加下属部门"); 25 | } 26 | 27 | @Override 28 | public OrganizationComponent getChild(String orgName) { 29 | if(getName().equals(orgName)){ 30 | return this; 31 | } 32 | return null; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/top/ss007/composite/CompositeClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.composite; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/3 15:22 9 | * @description 10 | */ 11 | public class CompositeClient { 12 | 13 | private OrganizationComponent constructOrganization() { 14 | //构建总部 15 | OrganizationComposite head = new OrganizationComposite("总公司"); 16 | AdminDepartment headAdmin = new AdminDepartment("总公司行政部"); 17 | ItDepartment headIt = new ItDepartment("总公司It部"); 18 | head.add(headAdmin); 19 | head.add(headIt); 20 | 21 | //构建分公司 22 | OrganizationComposite branch1 = new OrganizationComposite("天津分公司"); 23 | AdminDepartment branch1Admin = new AdminDepartment("天津分公司行政部"); 24 | ItDepartment branch1It = new ItDepartment("天津分公司It部"); 25 | branch1.add(branch1Admin); 26 | branch1.add(branch1It); 27 | 28 | //将分公司加入到head中 29 | head.add(branch1); 30 | 31 | return head; 32 | } 33 | 34 | public void listOrgInfo() { 35 | OrganizationComponent org = constructOrganization(); 36 | System.out.println(String.format("%s共有%d名员工", 37 | org.getName(), org.getStaffCount())); 38 | 39 | OrganizationComponent subOrg = org.getChild("天津分公司行政部"); 40 | System.out.println(String.format("%s共有%d名员工", 41 | subOrg.getName(), subOrg.getStaffCount())); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/top/ss007/composite/ItDepartment.java: -------------------------------------------------------------------------------- 1 | package top.ss007.composite; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/3 15:09 9 | * @description 10 | */ 11 | public class ItDepartment extends OrganizationComponent { 12 | 13 | public ItDepartment(String name) { 14 | super(name); 15 | } 16 | 17 | @Override 18 | public int getStaffCount() { 19 | return 20; 20 | } 21 | 22 | @Override 23 | public void add(OrganizationComponent organization) { 24 | throw new UnsupportedOperationException(this.getName()+"已经是最基本部门,无法增加下属部门"); 25 | } 26 | 27 | @Override 28 | public OrganizationComponent getChild(String orgName) { 29 | if(getName().equals(orgName)){ 30 | return this; 31 | } 32 | return null; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/top/ss007/composite/OrganizationComponent.java: -------------------------------------------------------------------------------- 1 | package top.ss007.composite; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/3 15:07 9 | * @description 10 | */ 11 | public abstract class OrganizationComponent { 12 | private String name; 13 | 14 | public OrganizationComponent(String name) { 15 | this.name = name; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public abstract void add(OrganizationComponent organization); 23 | 24 | public abstract OrganizationComponent getChild(String orgName); 25 | 26 | public abstract int getStaffCount(); 27 | 28 | @Override 29 | public String toString() { 30 | return name; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/top/ss007/composite/OrganizationComposite.java: -------------------------------------------------------------------------------- 1 | package top.ss007.composite; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Copyright (C) 2021 ShuSheng007 8 | * 完全享有此软件的著作权 9 | * 10 | * @author ShuSheng007 11 | * @time 2021/5/3 15:10 12 | * @description 13 | */ 14 | public class OrganizationComposite extends OrganizationComponent { 15 | 16 | //很关键,这体现了组合的思想 17 | private List organizations = new ArrayList<>(); 18 | 19 | public OrganizationComposite(String name) { 20 | super(name); 21 | } 22 | 23 | @Override 24 | public void add(OrganizationComponent organization) { 25 | organizations.add(organization); 26 | } 27 | 28 | @Override 29 | public OrganizationComponent getChild(String orgName) { 30 | for (OrganizationComponent org : organizations) { 31 | OrganizationComponent targetOrg = org.getChild(orgName); 32 | if (targetOrg != null) { 33 | return targetOrg; 34 | } 35 | } 36 | return null; 37 | } 38 | 39 | @Override 40 | public int getStaffCount() { 41 | int count = 0; 42 | for (OrganizationComponent organization : organizations) { 43 | count += organization.getStaffCount(); 44 | } 45 | return count; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/top/ss007/decorator/CoffeeDecorator.java: -------------------------------------------------------------------------------- 1 | package top.ss007.decorator; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/2 0:02 9 | * @description 10 | */ 11 | public abstract class CoffeeDecorator implements ICoffee { 12 | private ICoffee coffee; 13 | 14 | public CoffeeDecorator(ICoffee coffee) { 15 | this.coffee = coffee; 16 | } 17 | 18 | @Override 19 | public void makeCoffee() { 20 | coffee.makeCoffee(); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/top/ss007/decorator/DecoratorClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.decorator; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/2 0:05 9 | * @description 10 | */ 11 | public class DecoratorClient { 12 | 13 | public void makeCoffee() { 14 | //原味咖啡 15 | ICoffee coffee = new OriginalCoffee(); 16 | coffee.makeCoffee(); 17 | System.out.println(""); 18 | 19 | //加奶的咖啡 20 | coffee = new MilkDecorator(coffee); 21 | coffee.makeCoffee(); 22 | System.out.println(""); 23 | 24 | //先加奶后加糖的咖啡 25 | coffee = new SugarDecorator(coffee); 26 | coffee.makeCoffee(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/top/ss007/decorator/ICoffee.java: -------------------------------------------------------------------------------- 1 | package top.ss007.decorator; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/1 23:59 9 | * @description 10 | */ 11 | public interface ICoffee { 12 | void makeCoffee(); 13 | } 14 | -------------------------------------------------------------------------------- /src/top/ss007/decorator/MilkDecorator.java: -------------------------------------------------------------------------------- 1 | package top.ss007.decorator; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/2 0:03 9 | * @description 10 | */ 11 | public class MilkDecorator extends CoffeeDecorator { 12 | public MilkDecorator(ICoffee coffee) { 13 | super(coffee); 14 | } 15 | 16 | @Override 17 | public void makeCoffee() { 18 | super.makeCoffee(); 19 | addMilk(); 20 | } 21 | 22 | private void addMilk() { 23 | System.out.print("加奶 "); 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /src/top/ss007/decorator/OriginalCoffee.java: -------------------------------------------------------------------------------- 1 | package top.ss007.decorator; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/2 0:01 9 | * @description 10 | */ 11 | public class OriginalCoffee implements ICoffee { 12 | @Override 13 | public void makeCoffee() { 14 | System.out.print("原味咖啡 "); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/top/ss007/decorator/SugarDecorator.java: -------------------------------------------------------------------------------- 1 | package top.ss007.decorator; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/2 0:04 9 | * @description 10 | */ 11 | public class SugarDecorator extends CoffeeDecorator { 12 | public SugarDecorator(ICoffee coffee) { 13 | super(coffee); 14 | } 15 | 16 | @Override 17 | public void makeCoffee() { 18 | super.makeCoffee(); 19 | addSugar(); 20 | } 21 | 22 | private void addSugar() { 23 | System.out.print("加糖"); 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /src/top/ss007/facade/DeliverySys.java: -------------------------------------------------------------------------------- 1 | package top.ss007.facade; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/5 23:09 9 | * @description 10 | */ 11 | public class DeliverySys { 12 | 13 | public int getDeliveryTime(){ 14 | System.out.println("获取配送耗时"); 15 | return 30*60;//30分钟 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/top/ss007/facade/FacadeClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.facade; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/5 23:18 9 | * @description 10 | */ 11 | public class FacadeClient { 12 | public void printReport(){ 13 | new ReportFacade().generateReport(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/top/ss007/facade/OrderSys.java: -------------------------------------------------------------------------------- 1 | package top.ss007.facade; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/5 23:03 9 | * @description 10 | */ 11 | public class OrderSys { 12 | public String getOrderNum(){ 13 | System.out.println("获取订单号"); 14 | return "123456"; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/top/ss007/facade/PaymentSys.java: -------------------------------------------------------------------------------- 1 | package top.ss007.facade; 2 | 3 | import java.math.BigDecimal; 4 | 5 | /** 6 | * Copyright (C) 2021 ShuSheng007 7 | * 完全享有此软件的著作权 8 | * 9 | * @author ShuSheng007 10 | * @time 2021/5/5 23:05 11 | * @description 12 | */ 13 | public class PaymentSys { 14 | 15 | private OrderSys orderSys; 16 | 17 | public PaymentSys(OrderSys orderSys) { 18 | this.orderSys = orderSys; 19 | } 20 | 21 | public BigDecimal getOrderAccount(String orderNum){ 22 | System.out.println(String.format("获取%s订单支付金额",orderNum)); 23 | return BigDecimal.valueOf(500); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/top/ss007/facade/ReportFacade.java: -------------------------------------------------------------------------------- 1 | package top.ss007.facade; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/5 23:12 9 | * @description 10 | */ 11 | public class ReportFacade { 12 | 13 | public void generateReport() { 14 | OrderSys orderSys = new OrderSys(); 15 | PaymentSys paymentSys = new PaymentSys(orderSys); 16 | DeliverySys deliverySys = new DeliverySys(); 17 | 18 | final String orderNum = orderSys.getOrderNum(); 19 | System.out.println(String.format("\n报表\n--------------------------------------------\n" + 20 | "订单号:%s | 金额:%s元 | 配送耗时:%s分钟", 21 | orderNum, 22 | paymentSys.getOrderAccount(orderNum).toPlainString(), 23 | String.valueOf(deliverySys.getDeliveryTime() / 60)) 24 | ); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/top/ss007/factory/Computer.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/25. 5 | */ 6 | public abstract class Computer { 7 | public abstract void setOperationSystem(); 8 | } 9 | -------------------------------------------------------------------------------- /src/top/ss007/factory/FactoryPatternService.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory; 2 | 3 | 4 | import top.ss007.factory.abstractfactory.AbstractFactory; 5 | import top.ss007.factory.abstractfactory.AppleFactory; 6 | import top.ss007.factory.factorymethod.ComputerFactory; 7 | import top.ss007.factory.factorymethod.MacComputerFactory; 8 | import top.ss007.factory.simplefactory.SimpleComputerFactory; 9 | 10 | public class FactoryPatternService { 11 | 12 | public void makePcUseSimpleFactory() { 13 | Computer computer = SimpleComputerFactory.makeComputer("mi"); 14 | computer.setOperationSystem(); 15 | } 16 | 17 | public void makePcUseFactory(){ 18 | //需要创建哪个品牌的电脑就使用对应的工厂,此处想生产Mac,所以使用了MacComputerFactory 19 | ComputerFactory factory = new MacComputerFactory(); 20 | factory.makeComputer().setOperationSystem(); 21 | } 22 | 23 | public void makePcUseAbstractFactory(){ 24 | AbstractFactory appleFactory = new AppleFactory(); 25 | appleFactory.makeComputer().setOperationSystem(); 26 | appleFactory.makeMobilePhone().setOperationSystem(); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/top/ss007/factory/MacComputer.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/25. 5 | */ 6 | public class MacComputer extends Computer { 7 | @Override 8 | public void setOperationSystem() { 9 | System.out.println("Mac笔记本安装Mac系统"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/top/ss007/factory/MiComputer.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/25. 5 | */ 6 | public class MiComputer extends Computer { 7 | @Override 8 | public void setOperationSystem() { 9 | System.out.println("小米笔记本安装Win10系统"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/top/ss007/factory/abstractfactory/AbstractFactory.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory.abstractfactory; 2 | 3 | 4 | import top.ss007.factory.Computer; 5 | 6 | /** 7 | * Created by Ben.Wang on 2019/1/25. 8 | * 9 | * 抽象工厂模式,基于不同厂商不同产品线维度来考虑,例如一个厂商除了生产电脑,还生产手机,还有可能生产手表。。。 10 | */ 11 | public interface AbstractFactory { 12 | Computer makeComputer(); 13 | 14 | MobilePhone makeMobilePhone(); 15 | } 16 | -------------------------------------------------------------------------------- /src/top/ss007/factory/abstractfactory/AppleFactory.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory.abstractfactory; 2 | 3 | 4 | import top.ss007.factory.Computer; 5 | import top.ss007.factory.MacComputer; 6 | 7 | /** 8 | * Created by Ben.Wang on 2019/1/25. 9 | */ 10 | public class AppleFactory implements AbstractFactory { 11 | @Override 12 | public Computer makeComputer() { 13 | return new MacComputer(); 14 | } 15 | 16 | @Override 17 | public MobilePhone makeMobilePhone() { 18 | return new IPhone(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/top/ss007/factory/abstractfactory/IPhone.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory.abstractfactory; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/25. 5 | */ 6 | public class IPhone extends MobilePhone { 7 | @Override 8 | public void setOperationSystem() { 9 | System.out.println("苹果手机安装IOS系统"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/top/ss007/factory/abstractfactory/MiPhone.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory.abstractfactory; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/25. 5 | */ 6 | public class MiPhone extends MobilePhone { 7 | @Override 8 | public void setOperationSystem() { 9 | System.out.println("小米手机安装Android系统"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/top/ss007/factory/abstractfactory/MobilePhone.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory.abstractfactory; 2 | 3 | /** 4 | * Created by Ben.Wang on 2019/1/25. 5 | */ 6 | public abstract class MobilePhone { 7 | public abstract void setOperationSystem(); 8 | } 9 | -------------------------------------------------------------------------------- /src/top/ss007/factory/abstractfactory/XiaoMiFactory.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory.abstractfactory; 2 | 3 | 4 | import top.ss007.factory.Computer; 5 | import top.ss007.factory.MiComputer; 6 | 7 | /** 8 | * Created by Ben.Wang on 2019/1/25. 9 | */ 10 | public class XiaoMiFactory implements AbstractFactory { 11 | @Override 12 | public Computer makeComputer() { 13 | return new MiComputer(); 14 | } 15 | 16 | @Override 17 | public MobilePhone makeMobilePhone() { 18 | return new MiPhone(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/top/ss007/factory/factorymethod/ComputerFactory.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory.factorymethod; 2 | 3 | 4 | import top.ss007.factory.Computer; 5 | 6 | /** 7 | * Created by Ben.Wang on 2019/1/25. 8 | * 9 | * 工厂方法模式,同一种产品不同品牌,例如苹果PC和小米PC,都是PC 10 | */ 11 | public interface ComputerFactory { 12 | Computer makeComputer(); 13 | } 14 | -------------------------------------------------------------------------------- /src/top/ss007/factory/factorymethod/MacComputerFactory.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory.factorymethod; 2 | 3 | 4 | import top.ss007.factory.Computer; 5 | import top.ss007.factory.MacComputer; 6 | 7 | /** 8 | * Created by Ben.Wang on 2019/1/25. 9 | * 10 | */ 11 | public class MacComputerFactory implements ComputerFactory { 12 | @Override 13 | public Computer makeComputer() { 14 | return new MacComputer(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/top/ss007/factory/factorymethod/MiComputerFactory.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory.factorymethod; 2 | 3 | 4 | import top.ss007.factory.Computer; 5 | import top.ss007.factory.MiComputer; 6 | 7 | /** 8 | * Created by Ben.Wang on 2019/1/25. 9 | */ 10 | public class MiComputerFactory implements ComputerFactory { 11 | @Override 12 | public Computer makeComputer() { 13 | return new MiComputer(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/top/ss007/factory/simplefactory/SimpleComputerFactory.java: -------------------------------------------------------------------------------- 1 | package top.ss007.factory.simplefactory; 2 | 3 | 4 | import top.ss007.factory.Computer; 5 | import top.ss007.factory.MacComputer; 6 | import top.ss007.factory.MiComputer; 7 | 8 | /** 9 | * Created by Ben.Wang on 2019/1/25. 10 | * 增加新的产品需要修改此工厂类,违反开闭原则,降低内聚性 11 | */ 12 | public class SimpleComputerFactory { 13 | public static Computer makeComputer(String brand) { 14 | Computer computer = null; 15 | switch (brand) { 16 | case "mac": 17 | computer = new MacComputer(); 18 | break; 19 | case "mi": 20 | computer = new MiComputer(); 21 | break; 22 | default: 23 | break; 24 | } 25 | return computer; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/top/ss007/flyweight/BlackChess.java: -------------------------------------------------------------------------------- 1 | package top.ss007.flyweight; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/5 11:47 9 | * @description 10 | */ 11 | public class BlackChess implements Chess { 12 | //内部状态,共享 13 | private final Color color = Color.BLACK; 14 | 15 | private final String sharp = "圆形"; 16 | 17 | public Color getColor() { 18 | return color; 19 | } 20 | 21 | @Override 22 | public void draw(int x, int y) { 23 | System.out.println(String.format("%s%s棋子置于(%d,%d)处", sharp, color.getAlias(), x, y)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/top/ss007/flyweight/Chess.java: -------------------------------------------------------------------------------- 1 | package top.ss007.flyweight; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/5 11:44 9 | * @description 10 | */ 11 | public interface Chess { 12 | //绘制棋子 13 | void draw(int x,int y); 14 | } 15 | -------------------------------------------------------------------------------- /src/top/ss007/flyweight/ChessFactory.java: -------------------------------------------------------------------------------- 1 | package top.ss007.flyweight; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Copyright (C) 2021 ShuSheng007 8 | * 完全享有此软件的著作权 9 | * 10 | * @author ShuSheng007 11 | * @time 2021/5/5 11:55 12 | * @description 13 | */ 14 | public class ChessFactory { 15 | private static final Map chessMap = new HashMap<>(); 16 | 17 | public static Chess getChess(Color color) { 18 | Chess chess = chessMap.get(color); 19 | if (chess == null) { 20 | chess = color == Color.WHITE ? new WhiteChess() : new BlackChess(); 21 | chessMap.put(color, chess); 22 | } 23 | return chess; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/top/ss007/flyweight/Color.java: -------------------------------------------------------------------------------- 1 | package top.ss007.flyweight; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/5 11:48 9 | * @description 10 | */ 11 | public enum Color { 12 | BLACK("黑色"),WHITE("白色"); 13 | 14 | private String alias; 15 | 16 | Color(String alias) { 17 | this.alias= alias; 18 | } 19 | 20 | public String getAlias() { 21 | return alias; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/top/ss007/flyweight/FlyweightClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.flyweight; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/5 12:11 9 | * @description 10 | */ 11 | public class FlyweightClient { 12 | 13 | public void playChess() { 14 | //下黑子 15 | Chess backChess1 = ChessFactory.getChess(Color.BLACK); 16 | backChess1.draw(2, 5); 17 | 18 | //下白子 19 | Chess whiteChess = ChessFactory.getChess(Color.WHITE); 20 | whiteChess.draw(3, 5); 21 | 22 | //下黑子 23 | Chess backChess2 = ChessFactory.getChess(Color.BLACK); 24 | backChess2.draw(2, 6); 25 | 26 | System.out.println(String.format("backChess1:%d | backChess2:%d | whiteChess:%d", 27 | backChess1.hashCode(), backChess2.hashCode(), whiteChess.hashCode())); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/top/ss007/flyweight/WhiteChess.java: -------------------------------------------------------------------------------- 1 | package top.ss007.flyweight; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/5 11:47 9 | * @description 10 | */ 11 | public class WhiteChess implements Chess { 12 | //内部状态,共享 13 | private final Color color = Color.WHITE; 14 | 15 | private final String sharp = "圆形"; 16 | 17 | public Color getColor() { 18 | return color; 19 | } 20 | 21 | @Override 22 | public void draw(int x, int y) { 23 | System.out.println(String.format("%s%s棋子置于(%d,%d)处", sharp, color.getAlias(), x, y)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/top/ss007/iterator/Class.java: -------------------------------------------------------------------------------- 1 | package top.ss007.iterator; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.List; 6 | 7 | /** 8 | * Copyright (C) 2021 ShuSheng007 9 | * 完全享有此软件的著作权 10 | * 11 | * @author ShuSheng007 12 | * @time 2021/6/14 9:53 13 | * @description 14 | */ 15 | public class Class implements Iterable { 16 | private final List students = new ArrayList<>(); 17 | 18 | public Class() { 19 | students.add(new Student("王二狗", 28)); 20 | students.add(new Student("牛翠花", 20)); 21 | students.add(new Student("林蛋大", 29)); 22 | } 23 | 24 | public boolean addStudent(Student student){ 25 | return students.add(student); 26 | } 27 | 28 | public boolean removeStudent(Student student){ 29 | return students.remove(student); 30 | } 31 | 32 | @Override 33 | public Iterator iterator() { 34 | return new Itr(); 35 | } 36 | 37 | private class Itr implements Iterator { 38 | 39 | int index = 0; 40 | 41 | @Override 42 | public boolean hasNext() { 43 | if (index < students.size()) { 44 | return true; 45 | } 46 | return false; 47 | } 48 | 49 | @Override 50 | public Student next() { 51 | Student student = students.get(index); 52 | index++; 53 | return student; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/top/ss007/iterator/IteratorClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.iterator; 2 | 3 | import java.util.Iterator; 4 | 5 | /** 6 | * Copyright (C) 2021 ShuSheng007 7 | * 完全享有此软件的著作权 8 | * 9 | * @author ShuSheng007 10 | * @time 2021/6/14 15:31 11 | * @description 12 | */ 13 | public class IteratorClient { 14 | 15 | public void checkAttendance(){ 16 | Class cls= new Class(); 17 | System.out.println("--------------开始点名--------------"); 18 | Iterator iterator= cls.iterator(); 19 | while (iterator.hasNext()){ 20 | System.out.println(iterator.next()); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/top/ss007/iterator/Student.java: -------------------------------------------------------------------------------- 1 | package top.ss007.iterator; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * Copyright (C) 2021 ShuSheng007 7 | * 完全享有此软件的著作权 8 | * 9 | * @author ShuSheng007 10 | * @time 2021/6/14 15:13 11 | * @description 12 | */ 13 | public class Student { 14 | private String name; 15 | private int age; 16 | 17 | public Student(String name, int age) { 18 | this.name = name; 19 | this.age = age; 20 | } 21 | 22 | @Override 23 | public String toString() { 24 | return "Student{" + 25 | "name='" + name + '\'' + 26 | ", age=" + age + 27 | '}'; 28 | } 29 | 30 | @Override 31 | public boolean equals(Object o) { 32 | if (this == o) return true; 33 | if (o == null || getClass() != o.getClass()) return false; 34 | Student student = (Student) o; 35 | return name.equals(student.name); 36 | } 37 | 38 | @Override 39 | public int hashCode() { 40 | return Objects.hash(name); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/top/ss007/memento/GameCareTaker.java: -------------------------------------------------------------------------------- 1 | package top.ss007.memento; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Copyright (C) 2021 ShuSheng007 8 | * 完全享有此软件的著作权 9 | * 10 | * @author ShuSheng007 11 | * @time 2021/5/30 13:10 12 | * @description 13 | */ 14 | public class GameCareTaker { 15 | 16 | private List memento= new ArrayList<>(); 17 | 18 | public void saveMemento(GameProgressMemento memento) { 19 | this.memento.add(memento); 20 | } 21 | 22 | public GameProgressMemento getMemento(int index) { 23 | return this.memento.get(index); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/top/ss007/memento/GameOriginator.java: -------------------------------------------------------------------------------- 1 | package top.ss007.memento; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/30 13:10 9 | * @description 10 | */ 11 | public class GameOriginator { 12 | private int currentScore; 13 | 14 | //将需要保存的状态分装在Memento里对外提供 15 | public GameProgressMemento saveProcess() { 16 | return new GameProgressMemento(currentScore); 17 | } 18 | 19 | //通过从外部接收的Memento恢复状态 20 | public void restoreProcess(GameProgressMemento memento) { 21 | currentScore = memento.getScore(); 22 | } 23 | 24 | //对内部状态的使用 25 | public void playGame() { 26 | System.out.println("------------------开始游戏------------------"); 27 | System.out.println("当前分数为:"+ currentScore); 28 | System.out.println("杀死一个小怪物得1分"); 29 | currentScore++; 30 | System.out.println(String.format("总分为:%d", currentScore)); 31 | } 32 | 33 | public void exitGame(){ 34 | System.out.println("退出游戏"); 35 | currentScore=0; 36 | System.out.println("-----------------退出游戏-------------------"); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/top/ss007/memento/GameProgressMemento.java: -------------------------------------------------------------------------------- 1 | package top.ss007.memento; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/30 13:08 9 | * @description 10 | */ 11 | public class GameProgressMemento { 12 | private int score; 13 | 14 | public GameProgressMemento(int score) { 15 | this.score = score; 16 | } 17 | 18 | public int getScore() { 19 | return score; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/top/ss007/memento/MementoClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.memento; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/30 13:26 9 | * @description 10 | */ 11 | public class MementoClient { 12 | 13 | public void replayGame() { 14 | GameOriginator originator = new GameOriginator(); 15 | GameCareTaker careTaker = new GameCareTaker(); 16 | //玩游戏 17 | originator.playGame(); 18 | //保存进度 19 | careTaker.saveMemento(originator.saveProcess()); 20 | //退出游戏 21 | originator.exitGame(); 22 | 23 | //重新打开游戏,恢复进度 24 | originator.restoreProcess(careTaker.getMemento(0)); 25 | originator.playGame(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/top/ss007/observer/Dog2WangObserver.java: -------------------------------------------------------------------------------- 1 | package top.ss007.observer; 2 | 3 | /** 4 | * Created by shusheng007 5 | * 6 | * @author benwang 7 | * @date 2022/6/4 7:12 下午 8 | * @description: 9 | */ 10 | public class Dog2WangObserver implements TianDogObserver{ 11 | @Override 12 | public void update(String message) { 13 | if("肚子好饿".equals(message)){ 14 | System.out.println("二狗:半夜起来,翻墙出去步行2公里买女神最爱吃的小笼包... 上官:二狗,你真是个好人"); 15 | }else if("心情不好".equals(message)){ 16 | System.out.println("二狗:官哭着述说渣男怎么欺负的她...整整3个小时,全程安慰... 上官:二狗,你真是个好人"); 17 | }else { 18 | System.out.println("随叫随到..."); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/top/ss007/observer/GreenTeaBitchSubject.java: -------------------------------------------------------------------------------- 1 | package top.ss007.observer; 2 | 3 | /** 4 | * Created by shusheng007 5 | * 6 | * @author benwang 7 | * @date 2022/6/4 7:04 下午 8 | * @description: 9 | */ 10 | public interface GreenTeaBitchSubject { 11 | void add(TianDogObserver observer); 12 | 13 | void remove(TianDogObserver observer); 14 | 15 | void notifyState(String state); 16 | } 17 | -------------------------------------------------------------------------------- /src/top/ss007/observer/ObserverClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.observer; 2 | 3 | /** 4 | * Created by shusheng007 5 | * 6 | * @author benwang 7 | * @date 2022/6/4 5:52 下午 8 | * @description: 9 | */ 10 | public class ObserverClient { 11 | public void sendThink(){ 12 | GreenTeaBitchSubject subject = new ShangGuanSubject(); 13 | Dog2WangObserver dog2WangObserver = new Dog2WangObserver(); 14 | subject.add(dog2WangObserver); 15 | subject.add(new YinDangObserver()); 16 | System.out.println("------午夜12点,肚子好饿,找个人来买东西吃------"); 17 | subject.notifyState("肚子好饿"); 18 | System.out.println("------又被渣男甩了,有点小难过,找个人来安慰一下------"); 19 | subject.notifyState("心情不好"); 20 | 21 | System.out.println("------二狗终于看透了上官这个绿茶婊,和牛翠花走到了一起------"); 22 | subject.remove(dog2WangObserver); 23 | 24 | System.out.println("------上官又被渣男甩了,想找个人来安慰一下,却不见了那个好人的身影------"); 25 | subject.notifyState("心情不好"); 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/top/ss007/observer/ShangGuanSubject.java: -------------------------------------------------------------------------------- 1 | package top.ss007.observer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by shusheng007 8 | * 9 | * @author benwang 10 | * @date 2022/6/4 7:09 下午 11 | * @description: 12 | */ 13 | public class ShangGuanSubject implements GreenTeaBitchSubject{ 14 | private List tianDogs = new ArrayList<>(); 15 | 16 | @Override 17 | public void add(TianDogObserver observer) { 18 | tianDogs.add(observer); 19 | } 20 | 21 | @Override 22 | public void remove(TianDogObserver observer) { 23 | tianDogs.remove(observer); 24 | } 25 | 26 | @Override 27 | public void notifyState(String state) { 28 | for (TianDogObserver tianDog : tianDogs) { 29 | tianDog.update(state); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/top/ss007/observer/TianDogObserver.java: -------------------------------------------------------------------------------- 1 | package top.ss007.observer; 2 | 3 | /** 4 | * Created by shusheng007 5 | * 6 | * @author benwang 7 | * @date 2022/6/4 7:07 下午 8 | * @description: 9 | */ 10 | public interface TianDogObserver { 11 | void update(String message); 12 | } 13 | -------------------------------------------------------------------------------- /src/top/ss007/observer/YinDangObserver.java: -------------------------------------------------------------------------------- 1 | package top.ss007.observer; 2 | 3 | /** 4 | * Created by shusheng007 5 | * 6 | * @author benwang 7 | * @date 2022/6/4 7:19 下午 8 | * @description: 9 | */ 10 | public class YinDangObserver implements TianDogObserver{ 11 | 12 | @Override 13 | public void update(String message) { 14 | if("肚子好饿".equals(message)){ 15 | System.out.println("西门:是吗?那我下面给你吃啊?上官:讨厌拉..."); 16 | }else if("心情不好".equals(message)){ 17 | System.out.println("西门:南门那边新开了一家酒吧,晚上带你去放松一下吧... 上官:好嗨吆,感觉人生达到了高峰.."); 18 | }else { 19 | System.out.println("甜言蜜语..."); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/top/ss007/prototype/Prototype.java: -------------------------------------------------------------------------------- 1 | package top.ss007.prototype; 2 | 3 | public interface Prototype { 4 | Prototype copy(); 5 | } 6 | -------------------------------------------------------------------------------- /src/top/ss007/prototype/PrototypeClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.prototype; 2 | 3 | import java.util.List; 4 | 5 | public class PrototypeClient { 6 | public void getReport(){ 7 | //创建原型 8 | Report reportPrototype = new Report(); 9 | //耗费资源的操作 10 | reportPrototype.loadData(); 11 | 12 | //使用原型对象构建新的对象 13 | Report reportWithTitle = (Report) reportPrototype.copy(); 14 | List reportContent= reportWithTitle.getContents(); 15 | reportContent.add(0,"《江城子·密州出猎》"); 16 | reportContent.add(1,"----------------------------------------------------------"); 17 | 18 | for (String s : reportContent) { 19 | System.out.println(s); 20 | } 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/top/ss007/prototype/Report.java: -------------------------------------------------------------------------------- 1 | package top.ss007.prototype; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Report implements Prototype { 7 | private List parts; 8 | 9 | public Report() { 10 | this.parts = new ArrayList<>(); 11 | } 12 | 13 | public Report(List parts) { 14 | this.parts = parts; 15 | } 16 | 17 | public void loadData() { 18 | parts.add("老夫聊发少年狂,左牵黄,右擎苍,锦帽貂裘,千骑卷平冈。"); 19 | parts.add("为报倾城随太守,亲射虎,看孙郎。"); 20 | parts.add("酒酣胸胆尚开张,鬓微霜,又何妨!持节云中,何日遣冯唐?"); 21 | parts.add("会挽雕弓如满月,西北望,射天狼。"); 22 | } 23 | 24 | public List getContents() { 25 | return parts; 26 | } 27 | 28 | @Override 29 | public Prototype copy() { 30 | List cloneList = new ArrayList<>(parts); 31 | return new Report(cloneList); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/top/ss007/proxy/ILawSuit.java: -------------------------------------------------------------------------------- 1 | package top.ss007.proxy; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/2 0:14 9 | * @description 10 | */ 11 | public interface ILawSuit { 12 | void submit(String proof);//提起诉讼 13 | 14 | void defend();//法庭辩护 15 | } 16 | -------------------------------------------------------------------------------- /src/top/ss007/proxy/ProxyClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.proxy; 2 | 3 | import top.ss007.proxy.dynamicproxy.CuiHuaNiu; 4 | import top.ss007.proxy.dynamicproxy.DynProxyLawyer; 5 | import top.ss007.proxy.statictproxy.DogWang2; 6 | import top.ss007.proxy.statictproxy.ProxyLawyer; 7 | 8 | import java.lang.reflect.InvocationHandler; 9 | import java.lang.reflect.Proxy; 10 | 11 | /** 12 | * Copyright (C) 2021 ShuSheng007 13 | * 完全享有此软件的著作权 14 | * 15 | * @author ShuSheng007 16 | * @time 2021/5/2 0:18 17 | * @description 18 | */ 19 | public class ProxyClient { 20 | 21 | public void doyWang2IndictBos() { 22 | System.out.println("王二狗通过代理律师起诉马旭:"); 23 | ILawSuit lawyer = new ProxyLawyer(new DogWang2()); 24 | lawyer.submit("工资流水在此"); 25 | lawyer.defend(); 26 | } 27 | 28 | public void cuiHuaNiuIndictBos() { 29 | System.out.println("牛翠花通过代理律师起诉马旭:"); 30 | CuiHuaNiu cuiHuaNiu = new CuiHuaNiu(); 31 | InvocationHandler handler = new DynProxyLawyer(cuiHuaNiu); 32 | ILawSuit lawyer = (ILawSuit) Proxy.newProxyInstance(cuiHuaNiu.getClass().getClassLoader(), 33 | cuiHuaNiu.getClass().getInterfaces(), handler); 34 | 35 | lawyer.submit("工资流水在此"); 36 | lawyer.defend(); 37 | } 38 | 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/top/ss007/proxy/dynamicproxy/CuiHuaNiu.java: -------------------------------------------------------------------------------- 1 | package top.ss007.proxy.dynamicproxy; 2 | 3 | import top.ss007.proxy.ILawSuit; 4 | 5 | /** 6 | * Copyright (C) 2021 ShuSheng007 7 | * 完全享有此软件的著作权 8 | * 9 | * @author ShuSheng007 10 | * @time 2021/5/2 0:22 11 | * @description 12 | */ 13 | public class CuiHuaNiu implements ILawSuit { 14 | @Override 15 | public void submit(String proof) { 16 | System.out.println(String.format("老板欠薪跑路,证据如下:%s",proof)); 17 | } 18 | @Override 19 | public void defend() { 20 | System.out.println(String.format("铁证如山,%s还牛翠花血汗钱","马旭")); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/top/ss007/proxy/dynamicproxy/DynProxyLawyer.java: -------------------------------------------------------------------------------- 1 | package top.ss007.proxy.dynamicproxy; 2 | 3 | import java.lang.reflect.InvocationHandler; 4 | import java.lang.reflect.Method; 5 | 6 | /** 7 | * Copyright (C) 2021 ShuSheng007 8 | * 完全享有此软件的著作权 9 | * 10 | * @author ShuSheng007 11 | * @time 2021/5/2 0:22 12 | * @description 13 | */ 14 | public class DynProxyLawyer implements InvocationHandler { 15 | private Object target;//被代理的对象 16 | 17 | public DynProxyLawyer(Object obj) { 18 | this.target = obj; 19 | } 20 | 21 | @Override 22 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 23 | System.out.println("案件进展:" + method.getName()); 24 | Object result = method.invoke(target, args); 25 | return result; 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /src/top/ss007/proxy/statictproxy/DogWang2.java: -------------------------------------------------------------------------------- 1 | package top.ss007.proxy.statictproxy; 2 | 3 | import top.ss007.proxy.ILawSuit; 4 | 5 | /** 6 | * Copyright (C) 2021 ShuSheng007 7 | * 完全享有此软件的著作权 8 | * 9 | * @author ShuSheng007 10 | * @time 2021/5/2 0:15 11 | * @description 12 | */ 13 | public class DogWang2 implements ILawSuit { 14 | @Override 15 | public void submit(String proof) { 16 | System.out.println(String.format("老板欠薪跑路,证据如下:%s",proof)); 17 | } 18 | 19 | @Override 20 | public void defend() { 21 | System.out.println(String.format("铁证如山,%s还王二狗血汗钱","马旭")); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/top/ss007/proxy/statictproxy/ProxyLawyer.java: -------------------------------------------------------------------------------- 1 | package top.ss007.proxy.statictproxy; 2 | 3 | import top.ss007.proxy.ILawSuit; 4 | 5 | /** 6 | * Copyright (C) 2021 ShuSheng007 7 | * 完全享有此软件的著作权 8 | * 9 | * @author ShuSheng007 10 | * @time 2021/5/2 0:16 11 | * @description 12 | */ 13 | public class ProxyLawyer implements ILawSuit { 14 | 15 | ILawSuit plaintiff;//持有要代理的那个对象 16 | 17 | public ProxyLawyer(ILawSuit plaintiff) { 18 | this.plaintiff = plaintiff; 19 | } 20 | 21 | @Override 22 | public void submit(String proof) { 23 | plaintiff.submit(proof); 24 | } 25 | 26 | @Override 27 | public void defend() { 28 | plaintiff.defend(); 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /src/top/ss007/run/DesignPatternName.java: -------------------------------------------------------------------------------- 1 | package top.ss007.run; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | /** 8 | * Created by shusheng007 9 | * 10 | * @author benwang 11 | * @date 2022/10/15 11:49 12 | * @description: 13 | */ 14 | public enum DesignPatternName { 15 | ABSTRACT_FACTORY, 16 | FACTORY_METHOD, 17 | SIMPLE_FACTORY, 18 | BUILDER, 19 | PROTOTYPE, 20 | SINGLETON, 21 | 22 | BRIDGE, 23 | ADAPTER, 24 | DECORATOR, 25 | COMPOSITE, 26 | FLY_WEIGHT, 27 | FACADE, 28 | 29 | COMMAND, 30 | CHAIN_OF_RESPONSIBILITY, 31 | STRATEGY, 32 | TEMPLATE, 33 | PROXY, 34 | STATE, 35 | MEMENTO, 36 | ITERATOR, 37 | VISITOR, 38 | OBSERVER; 39 | 40 | public static List patterList() { 41 | return Arrays.stream(DesignPatternName.values()) 42 | .map(Enum::name) 43 | .collect(Collectors.toList()); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/top/ss007/run/PatternExecutor.java: -------------------------------------------------------------------------------- 1 | package top.ss007.run; 2 | 3 | import top.ss007.adapter.AdapterClient; 4 | import top.ss007.bridge.BridgeClient; 5 | import top.ss007.builder.BuilderPatternService; 6 | import top.ss007.chainofresponsibility.DogWang2Cor; 7 | import top.ss007.command.DogWang2Client; 8 | import top.ss007.composite.CompositeClient; 9 | import top.ss007.decorator.DecoratorClient; 10 | import top.ss007.facade.FacadeClient; 11 | import top.ss007.factory.FactoryPatternService; 12 | import top.ss007.flyweight.FlyweightClient; 13 | import top.ss007.iterator.IteratorClient; 14 | import top.ss007.memento.MementoClient; 15 | import top.ss007.observer.ObserverClient; 16 | import top.ss007.prototype.PrototypeClient; 17 | import top.ss007.proxy.ProxyClient; 18 | import top.ss007.singleton.SingletonClient; 19 | import top.ss007.state.StateClient; 20 | import top.ss007.strategy.StrategyClient; 21 | import top.ss007.template.TemplateClient; 22 | import top.ss007.visitor.VisitorClient; 23 | 24 | /** 25 | * Created by shusheng007 26 | * 27 | * @author benwang 28 | * @date 2022/10/15 11:53 29 | * @description: 30 | */ 31 | public class PatternExecutor { 32 | 33 | public void run(String pattern) throws IllegalArgumentException{ 34 | switch (DesignPatternName.valueOf(pattern)) { 35 | case COMMAND: 36 | runCommand(); 37 | break; 38 | case CHAIN_OF_RESPONSIBILITY: 39 | runChainOfResponsibility(); 40 | break; 41 | case BUILDER: 42 | runBuilder(); 43 | break; 44 | case SIMPLE_FACTORY: 45 | runSimpleFactory(); 46 | break; 47 | case FACTORY_METHOD: 48 | runFactoryMethod(); 49 | break; 50 | case ABSTRACT_FACTORY: 51 | runAbstractFactory(); 52 | break; 53 | case BRIDGE: 54 | runBridge(); 55 | break; 56 | case STRATEGY: 57 | runStrategy(); 58 | break; 59 | case TEMPLATE: 60 | runTemplate(); 61 | break; 62 | case ADAPTER: 63 | runAdapter(); 64 | break; 65 | case PROXY: 66 | runProxy(); 67 | break; 68 | case DECORATOR: 69 | runDecorator(); 70 | break; 71 | case STATE: 72 | runState(); 73 | break; 74 | case COMPOSITE: 75 | runComposite(); 76 | break; 77 | case FLY_WEIGHT: 78 | runFlyweight(); 79 | break; 80 | case FACADE: 81 | runFacade(); 82 | break; 83 | case PROTOTYPE: 84 | runPrototype(); 85 | break; 86 | case SINGLETON: 87 | runSingleton(); 88 | break; 89 | case MEMENTO: 90 | runMemento(); 91 | break; 92 | case VISITOR: 93 | runVisitor(); 94 | break; 95 | case ITERATOR: 96 | runIterator(); 97 | break; 98 | case OBSERVER: 99 | runObserver(); 100 | break; 101 | default: 102 | break; 103 | } 104 | } 105 | 106 | //region 创建型设计模式 107 | //构建者模式 108 | private static void runBuilder() { 109 | BuilderPatternService builder = new BuilderPatternService(); 110 | builder.assemblePcUseSimpleBuilder(); 111 | builder.assemblePcUseTraditionBuilder(); 112 | } 113 | 114 | //抽象工厂 115 | private static void runAbstractFactory() { 116 | FactoryPatternService factory = new FactoryPatternService(); 117 | factory.makePcUseAbstractFactory(); 118 | } 119 | 120 | //工厂方法 121 | private static void runFactoryMethod() { 122 | FactoryPatternService factory = new FactoryPatternService(); 123 | factory.makePcUseFactory(); 124 | } 125 | 126 | //简单工厂 127 | private static void runSimpleFactory() { 128 | FactoryPatternService factory = new FactoryPatternService(); 129 | factory.makePcUseSimpleFactory(); 130 | } 131 | 132 | //原型模式 133 | private static void runPrototype(){ 134 | PrototypeClient prototypeClient=new PrototypeClient(); 135 | prototypeClient.getReport(); 136 | 137 | } 138 | 139 | //单例模式 140 | private static void runSingleton(){ 141 | SingletonClient singletonClient =new SingletonClient(); 142 | singletonClient.run(); 143 | } 144 | //endregion 145 | 146 | //region 结构型设计模式 147 | //适配器模式 148 | private static void runAdapter() { 149 | AdapterClient adapterClient = new AdapterClient(); 150 | adapterClient.recordLog(); 151 | } 152 | 153 | //桥接模式 154 | private static void runBridge() { 155 | BridgeClient bridgeClient = new BridgeClient(); 156 | bridgeClient.orderOffer(); 157 | } 158 | 159 | //装饰器模式 160 | private static void runDecorator() { 161 | DecoratorClient decoratorClient = new DecoratorClient(); 162 | decoratorClient.makeCoffee(); 163 | } 164 | 165 | //代理模式 166 | private static void runProxy() { 167 | ProxyClient proxyClient = new ProxyClient(); 168 | proxyClient.doyWang2IndictBos(); 169 | System.out.println("-----------------------------------"); 170 | proxyClient.cuiHuaNiuIndictBos(); 171 | } 172 | 173 | //组合模式 174 | private static void runComposite() { 175 | CompositeClient compositeClient = new CompositeClient(); 176 | compositeClient.listOrgInfo(); 177 | } 178 | 179 | //享元模式 180 | private static void runFlyweight() { 181 | FlyweightClient flyweightClient = new FlyweightClient(); 182 | flyweightClient.playChess(); 183 | } 184 | 185 | //外观模式 186 | private static void runFacade() { 187 | FacadeClient facadeClient = new FacadeClient(); 188 | facadeClient.printReport(); 189 | } 190 | //endregion 191 | 192 | //region 行为型设计模式 193 | // 命令模式 194 | private static void runCommand() { 195 | DogWang2Client dogWang2 = new DogWang2Client(); 196 | dogWang2.enjoySexRobot(); 197 | } 198 | 199 | //责任连模式 200 | private static void runChainOfResponsibility() { 201 | DogWang2Cor dogWang2Cor = new DogWang2Cor(); 202 | dogWang2Cor.applyBudget(); 203 | } 204 | 205 | //策略模式 206 | private static void runStrategy() { 207 | StrategyClient strategyClient = new StrategyClient(); 208 | strategyClient.listFeeToTianJinEye(); 209 | } 210 | 211 | //模板方法 212 | private static void runTemplate() { 213 | TemplateClient templateClient = new TemplateClient(); 214 | templateClient.startLivePlay(); 215 | } 216 | 217 | //状态模式 218 | private static void runState() { 219 | StateClient stateClient = new StateClient(); 220 | stateClient.buyKeyboard(); 221 | } 222 | 223 | //备忘录模式 224 | private static void runMemento(){ 225 | MementoClient mementoClient=new MementoClient(); 226 | mementoClient.replayGame(); 227 | } 228 | 229 | //迭代器模式 230 | private static void runIterator(){ 231 | IteratorClient client = new IteratorClient(); 232 | client.checkAttendance(); 233 | } 234 | 235 | //访问者模式 236 | private static void runVisitor(){ 237 | VisitorClient visitorClient =new VisitorClient(); 238 | visitorClient.startProject(); 239 | } 240 | 241 | //观察者模式 242 | private static void runObserver(){ 243 | ObserverClient client = new ObserverClient(); 244 | client.sendThink(); 245 | } 246 | //endregion 247 | } 248 | -------------------------------------------------------------------------------- /src/top/ss007/singleton/Singleton1.java: -------------------------------------------------------------------------------- 1 | package top.ss007.singleton; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/25 23:12 9 | * @description 10 | */ 11 | public class Singleton1 { 12 | private final static Singleton1 INSTANCE= new Singleton1(); 13 | 14 | private Singleton1() { 15 | } 16 | 17 | public static Singleton1 getInstance(){ 18 | return INSTANCE; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/top/ss007/singleton/Singleton3.java: -------------------------------------------------------------------------------- 1 | package top.ss007.singleton; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/25 23:12 9 | * @description 10 | */ 11 | public class Singleton3 { 12 | private static Singleton3 instance; 13 | 14 | private Singleton3() { 15 | } 16 | 17 | public static synchronized Singleton3 getInstance() { 18 | if (instance == null) { 19 | instance = new Singleton3(); 20 | } 21 | return instance; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/top/ss007/singleton/Singleton4.java: -------------------------------------------------------------------------------- 1 | package top.ss007.singleton; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/25 23:12 9 | * @description 10 | */ 11 | public class Singleton4 { 12 | private static volatile Singleton4 instance; 13 | 14 | private Singleton4() { 15 | } 16 | 17 | public static Singleton4 getInstance() { 18 | if (instance == null) { 19 | synchronized (Singleton4.class) { 20 | if(instance ==null){ 21 | instance = new Singleton4(); 22 | } 23 | } 24 | } 25 | return instance; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/top/ss007/singleton/Singleton5.java: -------------------------------------------------------------------------------- 1 | package top.ss007.singleton; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/25 23:12 9 | * @description 10 | */ 11 | public class Singleton5 { 12 | 13 | private Singleton5() { 14 | } 15 | 16 | private static class SingletonInstance { 17 | private final static Singleton5 INSTANCE = new Singleton5(); 18 | } 19 | 20 | public static Singleton5 getInstance() { 21 | return SingletonInstance.INSTANCE; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/top/ss007/singleton/Singleton6.java: -------------------------------------------------------------------------------- 1 | package top.ss007.singleton; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/25 23:12 9 | * @description 10 | */ 11 | public enum Singleton6 { 12 | INSTANCE; 13 | } 14 | -------------------------------------------------------------------------------- /src/top/ss007/singleton/SingletonClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.singleton; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/30 9:50 9 | * @description 10 | */ 11 | public class SingletonClient { 12 | 13 | public void run() { 14 | final Singleton5 instance1 = Singleton5.getInstance(); 15 | final Singleton5 instance2 = Singleton5.getInstance(); 16 | System.out.println(String.format("实例1:%s 实例2:%s | 是否是同一实例:%s", 17 | instance1, instance1, instance1 == instance2)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/top/ss007/state/JdLogistics.java: -------------------------------------------------------------------------------- 1 | package top.ss007.state; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * Copyright (C) 2021 ShuSheng007 7 | * 完全享有此软件的著作权 8 | * 9 | * @author ShuSheng007 10 | * @time 2021/5/3 11:03 11 | * @description Context 负责在各State之间保持并切换状态 12 | */ 13 | public class JdLogistics { 14 | private LogisticsState logisticsState; 15 | 16 | public void setLogisticsState(LogisticsState logisticsState) { 17 | this.logisticsState = logisticsState; 18 | } 19 | 20 | public LogisticsState getLogisticsState() { 21 | return logisticsState; 22 | } 23 | 24 | public void doAction(){ 25 | Objects.requireNonNull(logisticsState); 26 | logisticsState.doAction(this); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/top/ss007/state/LogisticsState.java: -------------------------------------------------------------------------------- 1 | package top.ss007.state; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/3 10:40 9 | * @description 用于封装不同状态下的不同行为 10 | */ 11 | public interface LogisticsState { 12 | void doAction(JdLogistics context); 13 | } 14 | -------------------------------------------------------------------------------- /src/top/ss007/state/OrderState.java: -------------------------------------------------------------------------------- 1 | package top.ss007.state; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/3 11:07 9 | * @description 10 | */ 11 | public class OrderState implements LogisticsState { 12 | @Override 13 | public void doAction(JdLogistics context) { 14 | System.out.println("商家已经接单,正在处理中..."); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/top/ss007/state/ProductOutState.java: -------------------------------------------------------------------------------- 1 | package top.ss007.state; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/3 11:07 9 | * @description 10 | */ 11 | public class ProductOutState implements LogisticsState { 12 | @Override 13 | public void doAction(JdLogistics context) { 14 | System.out.println("商品已经出库..."); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/top/ss007/state/StateClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.state; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/3 11:11 9 | * @description 10 | */ 11 | public class StateClient { 12 | 13 | public void buyKeyboard() { 14 | //状态的保持与切换者 15 | JdLogistics jdLogistics = new JdLogistics(); 16 | 17 | //接单状态 18 | OrderState orderState = new OrderState(); 19 | jdLogistics.setLogisticsState(orderState); 20 | jdLogistics.doAction(); 21 | 22 | //出库状态 23 | ProductOutState productOutState = new ProductOutState(); 24 | jdLogistics.setLogisticsState(productOutState); 25 | jdLogistics.doAction(); 26 | 27 | //运输状态 28 | TransportState transportState = new TransportState(); 29 | jdLogistics.setLogisticsState(transportState); 30 | jdLogistics.doAction(); 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/top/ss007/state/TransportState.java: -------------------------------------------------------------------------------- 1 | package top.ss007.state; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/3 11:07 9 | * @description 10 | */ 11 | public class TransportState implements LogisticsState { 12 | 13 | @Override 14 | public void doAction(JdLogistics context) { 15 | System.out.println("商品正在运往天津分发中心"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/top/ss007/strategy/ByBus.java: -------------------------------------------------------------------------------- 1 | package top.ss007.strategy; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/1 23:21 9 | * @description 乘坐公交车算法 10 | */ 11 | 12 | public class ByBus implements CalculateStrategy { 13 | @Override 14 | public int calculateTrafficFee(int distance) { 15 | return distance < 10 ? 4 : 6; 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /src/top/ss007/strategy/ByDiDiExpress.java: -------------------------------------------------------------------------------- 1 | package top.ss007.strategy; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/1 23:22 9 | * @description 乘坐滴滴快车算法 10 | * 11 | * 小于3公里8块,大于3公里 起步费8块+每公里3块 12 | */ 13 | public class ByDiDiExpress implements CalculateStrategy { 14 | @Override 15 | public int calculateTrafficFee(int distance) { 16 | return distance < 3 ? 8 : (8 + (distance - 3) * 3); 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /src/top/ss007/strategy/BySharedBicycle.java: -------------------------------------------------------------------------------- 1 | package top.ss007.strategy; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/1 23:24 9 | * @description 骑共享单车算法 10 | */ 11 | public class BySharedBicycle implements CalculateStrategy { 12 | @Override 13 | public int calculateTrafficFee(int distance) { 14 | return 2; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/top/ss007/strategy/CalculateStrategy.java: -------------------------------------------------------------------------------- 1 | package top.ss007.strategy; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/1 23:20 9 | * @description 10 | */ 11 | public interface CalculateStrategy { 12 | int calculateTrafficFee(int distance); 13 | } 14 | -------------------------------------------------------------------------------- /src/top/ss007/strategy/StrategyClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.strategy; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/1 23:25 9 | * @description 10 | */ 11 | public class StrategyClient { 12 | 13 | public void listFeeToTianJinEye(){ 14 | TransportFeeCalculator calculator =new TransportFeeCalculator(); 15 | 16 | calculator.setCalculateStrategy(new BySharedBicycle()); 17 | System.out.println(String.format("骑共享单车到天津之眼的花费为:%d块人民币", 18 | calculator.getTransportFee(10))); 19 | 20 | calculator.setCalculateStrategy(new ByBus()); 21 | System.out.println(String.format("乘坐公交车到天津之眼的花费为:%d块人民币", 22 | calculator.getTransportFee(12))); 23 | 24 | calculator.setCalculateStrategy(new ByDiDiExpress()); 25 | System.out.println(String.format("乘坐滴滴快车到天津之眼的花费为:%d块人民币", 26 | calculator.getTransportFee(13))); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/top/ss007/strategy/TransportFeeCalculator.java: -------------------------------------------------------------------------------- 1 | package top.ss007.strategy; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * Copyright (C) 2021 ShuSheng007 7 | * 完全享有此软件的著作权 8 | * 9 | * @author ShuSheng007 10 | * @time 2021/5/3 11:28 11 | * @description 12 | */ 13 | public class TransportFeeCalculator { 14 | 15 | private CalculateStrategy calculateStrategy; 16 | 17 | public void setCalculateStrategy(CalculateStrategy calculateStrategy) { 18 | this.calculateStrategy = calculateStrategy; 19 | } 20 | 21 | public int getTransportFee(int distance){ 22 | Objects.requireNonNull(calculateStrategy); 23 | return calculateStrategy.calculateTrafficFee(distance); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/top/ss007/template/JinShanLivePlay.java: -------------------------------------------------------------------------------- 1 | package top.ss007.template; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/1 23:36 9 | * @description 10 | * 11 | * 由于金山SDK没有提供了旁路推流的功能,所以它不用覆写pushVideoStream()这个钩子方法,而只需要overwrite抽象方法即可 12 | */ 13 | public class JinShanLivePlay extends LivePlay { 14 | @Override 15 | public void openRoom() { 16 | System.out.println("金山打开房间"); 17 | } 18 | 19 | @Override 20 | public void startAudioAndVideoStream() { 21 | System.out.println("金山打开音视频流"); 22 | } 23 | 24 | @Override 25 | public void stopAudioAndVideoStream() { 26 | System.out.println("金山关闭音视频流"); 27 | } 28 | 29 | @Override 30 | public void closeRoom() { 31 | System.out.println("金山关闭房间"); 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/top/ss007/template/LivePlay.java: -------------------------------------------------------------------------------- 1 | package top.ss007.template; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/1 23:34 9 | * @description 10 | */ 11 | public abstract class LivePlay { 12 | //模板方法 13 | public final void seeLivePlay() { 14 | login(); 15 | openRoom(); 16 | startAudioAndVideoStream(); 17 | pushVideoStream(); 18 | stopAudioAndVideoStream(); 19 | closeRoom(); 20 | } 21 | 22 | //实体方法,这个方法实现通用的业务逻辑 23 | private void login() { 24 | System.out.println("用户登录"); 25 | } 26 | 27 | /*抽象方法*/ 28 | //打开房间 29 | public abstract void openRoom(); 30 | //打开音视频流 31 | public abstract void startAudioAndVideoStream(); 32 | //关闭音视频流 33 | public abstract void stopAudioAndVideoStream(); 34 | //关闭房间 35 | public abstract void closeRoom(); 36 | 37 | /*钩子方法,可以被需要的子类overwrite*/ 38 | //旁路推流,可以通过视频链接在浏览器中查看视频 39 | public void pushVideoStream() { 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/top/ss007/template/TemplateClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.template; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/1 23:38 9 | * @description 10 | */ 11 | public class TemplateClient { 12 | 13 | public void startLivePlay() { 14 | LivePlay tencentLive = new TencentLivePlay(); 15 | tencentLive.seeLivePlay(); 16 | 17 | System.out.println("-----------切换视频流服务商-------------"); 18 | 19 | LivePlay jinShanLive = new JinShanLivePlay(); 20 | jinShanLive.seeLivePlay(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/top/ss007/template/TencentLivePlay.java: -------------------------------------------------------------------------------- 1 | package top.ss007.template; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/5/1 23:35 9 | * @description 10 | */ 11 | public class TencentLivePlay extends LivePlay { 12 | @Override 13 | public void openRoom() { 14 | System.out.println("腾讯打开房间"); 15 | } 16 | 17 | @Override 18 | public void startAudioAndVideoStream() { 19 | System.out.println("腾讯打开音视频流"); 20 | } 21 | 22 | @Override 23 | public void stopAudioAndVideoStream() { 24 | System.out.println("腾讯关闭音视频流"); 25 | } 26 | 27 | @Override 28 | public void closeRoom() { 29 | System.out.println("腾讯关闭房间"); 30 | } 31 | //覆写钩子方法,提供旁路推流功能 32 | @Override 33 | public void pushVideoStream() { 34 | super.pushVideoStream(); 35 | System.out.println("腾讯进行旁路推流"); 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/top/ss007/visitor/BigHuYouCompany.java: -------------------------------------------------------------------------------- 1 | package top.ss007.visitor; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Copyright (C) 2021 ShuSheng007 8 | * 完全享有此软件的著作权 9 | * 10 | * @author ShuSheng007 11 | * @time 2021/6/7 23:01 12 | * @description 13 | */ 14 | public class BigHuYouCompany { 15 | private List employee= new ArrayList<>(); 16 | 17 | public BigHuYouCompany() { 18 | employee.add(new Programmer("王二狗")); 19 | employee.add(new HumanSource("上官无需")); 20 | employee.add(new Tester("牛翠花")); 21 | } 22 | 23 | public void startProject(CorporateSlaveVisitor visitor){ 24 | for (CorporateSlave slave : employee) { 25 | slave.accept(visitor); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/top/ss007/visitor/CorporateSlave.java: -------------------------------------------------------------------------------- 1 | package top.ss007.visitor; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/6/7 21:53 9 | * @description 10 | */ 11 | public interface CorporateSlave { 12 | void accept(CorporateSlaveVisitor visitor); 13 | } 14 | -------------------------------------------------------------------------------- /src/top/ss007/visitor/CorporateSlaveVisitor.java: -------------------------------------------------------------------------------- 1 | package top.ss007.visitor; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/6/7 21:54 9 | * @description 10 | */ 11 | public interface CorporateSlaveVisitor { 12 | void visit(Programmer programmer); 13 | 14 | void visit(HumanSource humanSource); 15 | 16 | void visit(Tester tester); 17 | } 18 | -------------------------------------------------------------------------------- /src/top/ss007/visitor/HumanSource.java: -------------------------------------------------------------------------------- 1 | package top.ss007.visitor; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/6/7 22:00 9 | * @description 10 | */ 11 | public class HumanSource implements CorporateSlave { 12 | private String name; 13 | 14 | public HumanSource(String name) { 15 | this.name = name; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | @Override 23 | public void accept(CorporateSlaveVisitor visitor) { 24 | visitor.visit(this); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/top/ss007/visitor/LiveApp.java: -------------------------------------------------------------------------------- 1 | package top.ss007.visitor; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/6/7 22:04 9 | * @description 10 | */ 11 | public class LiveApp implements CorporateSlaveVisitor { 12 | @Override 13 | public void visit(Programmer programmer) { 14 | System.out.println(String.format("%s: 最近小视频很火啊,咱能不能抄袭下抖音,搞他一炮,将来公司上市了,你的身价至少也是几千万,甚至上亿...",programmer.getName())); 15 | } 16 | 17 | @Override 18 | public void visit(HumanSource humanSource) { 19 | System.out.println(String.format("%s: 咱公司就数你长得靓,哪天化化妆,把你的事业线适当露一露,要是火了你在北京买房都不是梦...",humanSource.getName())); 20 | } 21 | 22 | @Override 23 | public void visit(Tester tester) { 24 | System.out.println(String.format("%s: 你也开个账户,边测试边直播,两不耽误...",tester.getName())); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/top/ss007/visitor/Programmer.java: -------------------------------------------------------------------------------- 1 | package top.ss007.visitor; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/6/7 21:58 9 | * @description 10 | */ 11 | public class Programmer implements CorporateSlave { 12 | private String name; 13 | 14 | public Programmer(String name) { 15 | this.name = name; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | @Override 23 | public void accept(CorporateSlaveVisitor visitor) { 24 | visitor.visit(this); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/top/ss007/visitor/SocialApp.java: -------------------------------------------------------------------------------- 1 | package top.ss007.visitor; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/6/7 22:04 9 | * @description 10 | */ 11 | public class SocialApp implements CorporateSlaveVisitor { 12 | @Override 13 | public void visit(Programmer programmer) { 14 | System.out.println(String.format("%s: 给你一个月,先仿照微信搞个类似的APP出来,要能语音能发红包,将来公司上市了少不了你的,好好干...",programmer.getName())); 15 | } 16 | 17 | @Override 18 | public void visit(HumanSource humanSource) { 19 | System.out.println(String.format("%s: 咱现在缺人,你暂时就充当了陪聊吧,在程序员开发APP期间,你去发发软文,积攒点粉丝...",humanSource.getName())); 20 | } 21 | 22 | @Override 23 | public void visit(Tester tester) { 24 | System.out.println(String.format("%s: 这是咱创业的第一炮,一定要打响,测试不能掉链子啊,不能让APP带伤上战场,以后给你多招点人,你就是领导了...",tester.getName())); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/top/ss007/visitor/Tester.java: -------------------------------------------------------------------------------- 1 | package top.ss007.visitor; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/6/7 22:02 9 | * @description 10 | */ 11 | public class Tester implements CorporateSlave { 12 | 13 | private String name; 14 | 15 | public Tester(String name) { 16 | this.name = name; 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | @Override 24 | public void accept(CorporateSlaveVisitor visitor) { 25 | visitor.visit(this); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/top/ss007/visitor/VisitorClient.java: -------------------------------------------------------------------------------- 1 | package top.ss007.visitor; 2 | 3 | /** 4 | * Copyright (C) 2021 ShuSheng007 5 | * 完全享有此软件的著作权 6 | * 7 | * @author ShuSheng007 8 | * @time 2021/6/7 23:06 9 | * @description 10 | */ 11 | public class VisitorClient { 12 | 13 | public void startProject(){ 14 | BigHuYouCompany bigHuYou= new BigHuYouCompany(); 15 | //可以很轻松的更换Visitor,但是要求BigHuYouCompany的结构稳定 16 | System.out.println("-----------------启动社交APP项目--------------------"); 17 | bigHuYou.startProject(new SocialApp()); 18 | System.out.println("-----------------启动短视频APP项目--------------------"); 19 | bigHuYou.startProject(new LiveApp()); 20 | } 21 | } 22 | --------------------------------------------------------------------------------