├── LICENSE └── README.md /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 2021 Berk Berber 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 | [![GitHub license](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0) 2 | # Design-Patterns-in-Kotlin 3 | This repository is my knowledge sharing repository which is about Design Patterns, Object Oriented Programming concepts and SOLID principles. I have shared my knowledge about these subjects briefly and I have given simple examples for each subject 4 | 5 | # Contents 6 | 1. [Object Oriented Programming](#object-oriented-programming) 7 | - [Object Oriented Programming Concepts](#object-oriented-programming-concepts) 8 | - [Encapsulation](#encapsulation) 9 | - [Abstraction](#abstraction) 10 | - [Inheritance](#inheritance) 11 | - [Polymorphism](#polymorphism) 12 | 2. [SOLID Principles](#solid-principles) 13 | - [Single Responsibility Principle](#single-responsibility-principle) 14 | - [Open-Closed Principle](#open-closed-principle) 15 | - [Liskov Substitution Principle](#liskov-substitution-principle) 16 | - [Interface Segregation Principle](#interface-segregation-principle) 17 | - [Dependency Inversion Principle](#dependency-inversion-principle) 18 | 3. [Design Patterns](#design-patterns) 19 | - [Creational Design Patterns](#creational-design-patterns) 20 | - [Singleton Pattern](#singleton-pattern) 21 | - [Factory Method Pattern](#factory-method-pattern) 22 | - [Abstract Factory Pattern](#abstract-factory-pattern) 23 | - [Builder Pattern](#builder-pattern) 24 | - [Prototype Pattern](#prototype-pattern) 25 | - [Structural Design Patterns](#structural-design-patterns) 26 | 27 | # Object Oriented Programming 28 | Object oriented programming(OOP) is a programming paradigm which depends on classes and objects. It helps software developers to structure their codes and make them reusable pieces.

29 | Software developers are creating many different classes for that.
30 | Classes are user defined data types which have their own attributes and methods. These methods can determine the logical operations of the class. And attributes can hold data which a class can have.
31 | We can create as many instances from a class as we want. These instances are called as object. 32 | 33 | ## Object Oriented Programming Concepts 34 | Object-oriented programming has four basic concepts. These concepts might seem a little bit complex to you, if you are not familiar with them before. But understanding the how these concepts are working may help you so much for your software development career. 35 | 36 | ### Encapsulation 37 | Encapsulation means the attributes of a class is hidden from any other class and can be accessed only through any member methods of own class in which attributes are declared.
38 | To do that, we can define attributes as private. Then, we can add getter-setter methods as public for an attribute.
39 | There are 3 visibility types for variables and methods. These are: 40 | - public: If variables or methods are defined as public, can be accessed from any other class.. 41 | - private: If variables or methods are defined as private, can be accessed only in the class which we have defined the variables or methods. 42 | - protected: If variables or methods are defined as protected, can only be accessed from within the class in which variables or methods were defined, or within other classes which have extended from that class which have variables or methods. 43 | 44 | I will give you an example about encapsulation. But we don't need to worry about encapsulation in Kotlin. I will explain the reason after I give you the code 45 | ```kotlin 46 | class EncapsulationExample { 47 | private var testString: String = "" 48 | private var testInteger: Int = 0 49 | } 50 | ``` 51 | We don't need to worry about encapsulation in Kotlin. Because Kotlin compiler for JVM compiles Kotlin source files into Java class files. Thus, our code will be compiled as below:
52 | (Name of the class won't change. I changed it to make it more understandable.) 53 | ```java 54 | public class EncapsulationCompiled { 55 | private String testString = ""; 56 | private int testInteger = 0; 57 | 58 | public String getTestString() { 59 | return testString; 60 | } 61 | 62 | public void setTestString(String testString) { 63 | this.testString = testString; 64 | } 65 | 66 | public int getTestInteger() { 67 | return testInteger; 68 | } 69 | 70 | public void setTestInteger(int testInteger) { 71 | this.testInteger = testInteger; 72 | } 73 | } 74 | ``` 75 | 76 | ### Abstraction 77 | Abstraction is a process of hiding the internal details of a class from the outer world.
78 | We can define abstract methods or abstract classes. If one class has one abstract method at least, that means that class can be abstract class. Abstract classes are generally used to gather objects with common properties under one roof. 79 | ```kotlin 80 | abstract class AbstractionExample{ 81 | abstract fun abstractMethod() 82 | 83 | fun methodWithBody(){ 84 | println("This method has a body.") 85 | } 86 | } 87 | ``` 88 | But, if all methods are abstract methods and there is not any method with a body, that means this is an interface. 89 | ```java 90 | interface InterfaceExample { 91 | fun methodOne() 92 | fun methodTwo() 93 | } 94 | ``` 95 | 96 | ### Inheritance 97 | Inheritance means that one class acquires the attributes and methods of another class. That means, we can create new classes over existing classes.
98 | Main purpose of inheritance is to provide the reusability of code. So, a class has to write only the unique attributes and methods. Rest of the common attributes and methods can be extended from the another class.
99 | Here, two new terms come up. Parent class and child class. 100 | - Parent Class: This the class whose attributes and methods will be using by child class. 101 | - Child Class: This is class that extends the features of parent class. 102 | 103 | Note: If we want to create extendable class (parent class) in Kotlin, we should add 'open' keyword before 'class' keyword. Otherwise, we can't extend this class from other classes. As same with classes, if we want to override a method in child class, we should add 'open' keyword before 'fun' keyword in parent class. 104 | ```kotlin 105 | open class InheritanceParentClass{ 106 | var attributeParentClass1 = "Attribute in Parent Class" 107 | private var attributeParentClass2 = "We can't reach this attribute in child class. Because we defined it as private" 108 | 109 | fun methodParentClass1() = "This is first method in InheritanceParentClass" 110 | 111 | open fun methodParentClass2() = "This is second method in InheritanceParentClass. We will override this one." 112 | } 113 | ``` 114 | As we learnt in Encapsulation section, we can't reach attributes or methods in child class, which have defined as private in parent class. So if we want them to usable in child class, we shouldn't add private keyword. 115 | ```kotlin 116 | class InheritanceChildClass: InheritanceParentClass() { 117 | fun methodChildClass1() = "This is first method in InheritanceParentClass" 118 | 119 | override fun methodParentClass2() = "This method has overridden in child class" 120 | 121 | fun printAttributeParentClass1(){ 122 | println("$attributeParentClass1") 123 | attributeParentClass1 = "Attribute in Child Class" 124 | println("$attributeParentClass1") 125 | } 126 | } 127 | ``` 128 | I will give very basic main method to print these methods 129 | ```kotlin 130 | fun main(){ 131 | var parentClass = InheritanceParentClass() 132 | var childClass = InheritanceChildClass() 133 | 134 | println("Parent Class - methodParentClass1: ${parentClass.methodParentClass1()}") 135 | println("Parent Class - methodParentClass2: ${parentClass.methodParentClass2()}") 136 | 137 | println("Child Class - methodChildClass1: ${childClass.methodChildClass1()}") 138 | println("Child Class - methodParentClass2: ${childClass.methodParentClass2()}") 139 | childClass.printAttributeParentClass1() 140 | } 141 | ``` 142 | Output 143 | ``` 144 | Parent Class - methodParentClass1: This is first method in InheritanceParentClass 145 | Parent Class - methodParentClass2: This is second method in InheritanceParentClass. We will override this one. 146 | Child Class - methodChildClass1: This is first method in InheritanceParentClass 147 | Child Class - methodParentClass2: This method has overridden in child class 148 | Attribute in Parent Class 149 | Attribute in Child Class 150 | ``` 151 | 152 | ### Polymorphism 153 | With the help of polymorphism we can perform a single action in different ways. To do that, we need to define one interface, class or abstract class and we will have multiple implementations.
154 | I will give a brief example. You will see that, with the help of polymorphism, a method can perform different operations based on the object that it is acting upon.

155 | First, we will have parent class called as 'PolymorphismBaseClass' 156 | ```kotlin 157 | open abstract class PolymorphismBaseClass { 158 | open fun runMobileServiceOnDevice(){ 159 | println("This device is not running any mobile services.") 160 | } 161 | 162 | abstract fun mobileServicesName(): String 163 | } 164 | ``` 165 | Then we can create child classes from this parent class. Our child classes will use same method. These methods will do different but similar operations. 166 | ```kotlin 167 | class PolymorphismHuaweiClass: PolymorphismBaseClass() { 168 | override fun runMobileServiceOnDevice() { 169 | println("This device can work with Huawei Mobile Services.") 170 | } 171 | 172 | override fun mobileServicesName(): String = "Huawei Mobile Services" 173 | } 174 | ``` 175 | ```kotlin 176 | class PolymorphismGoogleClass: PolymorphismBaseClass() { 177 | override fun runMobileServiceOnDevice() { 178 | println("This device can work with Google Mobile Services.") 179 | } 180 | 181 | override fun mobileServicesName(): String = "Google Mobile Services" 182 | } 183 | ``` 184 | 185 | # SOLID Principles 186 | In object-oriented computer programming, SOLID is design principles intended to make software more understandable, flexible and maintainable.
187 | SOLID helps us to write sustainable code while developing software. This means, when software requirements have changed or we want to make additions to existing software, the system won't resist this. We will add new requiremements and functions easily. In addition to these, there are reasons such as maintenance and being easy to understand. 188 | 189 | ## Single Responsibility Principle 190 | Single-responsibility principle means that every module, class or method in a computer program should have responsibility over a single part of that program's functionality.
191 | We shouldn't have objects which know too much and have unnecessary behavior. So, a class will do only one job. Thus, this class should have only one reason to change.

192 | For example, let's think that we have class called as user which holds the information about user. Then we will add sign in and sign out methods for this user to manage authentication operations. 193 | ```kotlin 194 | data class User( 195 | var id: Long, 196 | var name: String, 197 | var password: String 198 | ){ 199 | fun signIn(){ 200 | // This method will do signing in operations 201 | } 202 | 203 | fun signOut(){ 204 | // This method will do signing out operations 205 | } 206 | } 207 | ``` 208 | But as you have learned with Single Responsibility Principle, all classes should have responsibility for a single process of a program.
209 | If we would like to make some changes for authentication process in sign in or sign out methods, our User class will be affected too. So, we will add more than one responsibility to one class. We shouldn't do that and we should separate our classes.
210 | That means, User class should do operations for only holding informations of the user. If we would like to manage authentication process of user like signing in and signing out, we should add a new class to manage authentication process. 211 | ```kotlin 212 | data class User( 213 | var id: Long, 214 | var name: String, 215 | var password: String 216 | ) 217 | 218 | class AuthenticationService(){ 219 | fun signIn(){ 220 | // This method will do signing in operations 221 | } 222 | 223 | fun signOut(){ 224 | // This method will do signing out operations 225 | } 226 | } 227 | ``` 228 | 229 | ## Open-Closed Principle 230 | There are two different important meanings for this principle. 231 | - Open: Means that we can add new features to class. When there are some changes on our dependencies, we should be able to add new features to our class easily 232 | - Closed: Means that base features of class shouldn't be able to change 233 | Let's imagine that we have a MobilePhoneUser class which is holding mobile phone and mobile services. This class will do operations for users' mobile phones by working with mobile services. And there are 2 different mobile services(HMS and GMS) 234 | ```kotlin 235 | class MobilePhone{ 236 | lateinit var brandName: String 237 | } 238 | 239 | class MobilePhoneUser{ 240 | fun runMobileDevice(mobileServices: Any, mobilePhone: MobilePhone){ 241 | if(mobileServices is HuaweiMobileServices) 242 | println("This device is running with Huawei Mobile Services") 243 | } 244 | } 245 | 246 | class HuaweiMobileServices{ 247 | fun addMobileServiceToPhone(mobilePhone: MobilePhone){ println("Huawei Mobile Services") } 248 | } 249 | ``` 250 | In the above code, we are checking mobile service type with if-else condition. This is a bad example, because when we want to add new mobile services, we will always need to check mobile services with if-else conditions.
251 | According to Open-Closed Principle, we should add one interface for all mobile services. Then, each mobile service types will implement this interface and will do their own business. Thus, we won't need to check mobile service type to make different operations 252 | ```kotlin 253 | class MobilePhone{ 254 | lateinit var brandName: String 255 | } 256 | 257 | class MobilePhoneUser{ 258 | fun runMobileDevice(mobileServices: IMobileServices, mobilePhone: MobilePhone){ 259 | mobileServices.addMobileServiceToPhone(mobilePhone) 260 | } 261 | } 262 | 263 | interface IMobileServices{ 264 | fun addMobileServiceToPhone(mobilePhone: MobilePhone) 265 | } 266 | 267 | class HuaweiMobileServices: IMobileServices{ 268 | override fun addMobileServiceToPhone(mobilePhone: MobilePhone){ println("Huawei Mobile Services") } 269 | } 270 | 271 | class GoogleMobileServices: IMobileServices{ 272 | override fun addMobileServiceToPhone(mobilePhone: MobilePhone){ println("Google Mobile Services") } 273 | } 274 | ``` 275 | 276 | ## Liskov Substitution Principle 277 | We should be able to use subclasses instead of the parent classes which class they have extended, without the need to make any changes in our code. In simple words, child class must be substitutable for the parent class.
278 | Since child classes extended from the parent classes, they inherit their behavior. If child classes can not perform the behaviors belonging to the parent classes, probably, we won't write any code in the method that does the behavior or we will throw an error when objects want to use it. But these actions cause code pollution and unnecessary code crowds.

279 | Let's think that we have an abstract class called as Vehicle. This abstract class have some methods about engine situation and moving forward/back. When we want to create child classes such as Car, Truck and etc. to extend Vehicle abstract class will be fine for us. 280 | ```kotlin 281 | abstract class Vehicle{ 282 | protected var isEngineWorking = false 283 | abstract fun startEngine() 284 | abstract fun stopEngine() 285 | abstract fun moveForward() 286 | abstract fun moveBack() 287 | } 288 | 289 | class Car: Vehicle(){ 290 | override fun startEngine() { 291 | println("Engine started") 292 | isEngineWorking = true 293 | } 294 | 295 | override fun stopEngine() { 296 | println("Engine stopped") 297 | isEngineWorking = false 298 | } 299 | 300 | override fun moveForward() { 301 | println("Moving forward") 302 | } 303 | 304 | override fun moveBack() { 305 | println("Moving back") 306 | } 307 | } 308 | 309 | class Bicycle: Vehicle(){ 310 | override fun startEngine() { 311 | // TODO("Not yet implemented") 312 | } 313 | 314 | override fun stopEngine() { 315 | // TODO("Not yet implemented") 316 | } 317 | 318 | override fun moveForward() { 319 | println("Moving forward") 320 | } 321 | 322 | override fun moveBack() { 323 | println("Moving back") 324 | } 325 | } 326 | ``` 327 | But as you see in the above code, when we want to create child class called as Bicycle, it's startEngine and stopEngine methods will be unnecessary. Because bicycles don't have an engine.
328 | To fix this situation, we can create a new child class which will extend the Vehicle. This class will work with vehicles which will have an engine. 329 | ```kotlin 330 | interface Vehicle{ 331 | fun moveForward() 332 | fun moveBack() 333 | } 334 | 335 | abstract class VehicleWithEngine: Vehicle{ 336 | private var isEngineWorking = false 337 | open fun startEngine(){ isEngineWorking = true } 338 | open fun stopEngine(){ isEngineWorking = false } 339 | } 340 | 341 | class Car: VehicleWithEngine(){ 342 | override fun startEngine() { 343 | super.startEngine() 344 | println("Engine started") 345 | } 346 | 347 | override fun stopEngine() { 348 | super.stopEngine() 349 | println("Engine stopped") 350 | } 351 | 352 | override fun moveForward() { 353 | println("Moving forward") 354 | } 355 | 356 | override fun moveBack() { 357 | println("Moving back") 358 | } 359 | } 360 | 361 | class Bicycle: Vehicle{ 362 | override fun moveForward() { 363 | println("Moving forward") 364 | } 365 | 366 | override fun moveBack() { 367 | println("Moving back") 368 | } 369 | } 370 | ``` 371 | 372 | ## Interface Segregation Principle 373 | In object-oriented programming, interfaces provide layers of abstraction that simplify code and create barriers which are preventing coupling to dependencies. Classes shouldn't implement interfaces which they are not going to use.
374 | Programming languages support multiple interface implementation. So, if there are some methods which won't be implemented by some type of classes, we should separate these interface to different interfaces.

375 | 376 | So let's think that we have an animal interface. And this interface will have methods about behaviors which animals can do. Thus, animals can use this interface to behave. 377 | ```kotlin 378 | interface Animal{ 379 | fun eat() 380 | fun sleep() 381 | fun fly() 382 | } 383 | 384 | class Cat: Animal{ 385 | override fun eat() { 386 | println("Cat is eating fish") 387 | } 388 | 389 | override fun sleep() { 390 | println("Cat is sleeping on its owner's bed") 391 | } 392 | 393 | override fun fly() { 394 | TODO("Not yet implemented") // Cats can't fly 395 | } 396 | } 397 | 398 | class Bird: Animal{ 399 | override fun eat() { 400 | println("Bird is eating forage") 401 | } 402 | 403 | override fun sleep() { 404 | println("Bird is sleeping in the nest") 405 | } 406 | 407 | override fun fly() { 408 | println("Bird is flying so high") 409 | } 410 | } 411 | ``` 412 | As you see, some animals can't fly such as cat. When we will create classes for these animals, it will be unnecessary to implement fly method.
413 | To fix that issue, we will create new interface called as FlyingAnimal. We will remove fly method from Animal interface and we will add it to out new interface 414 | ```kotlin 415 | interface Animal{ 416 | fun eat() 417 | fun sleep() 418 | } 419 | 420 | interface FlyingAnimal{ 421 | fun fly() 422 | } 423 | 424 | class Cat: Animal{ 425 | override fun eat() { 426 | println("Cat is eating fish") 427 | } 428 | 429 | override fun sleep() { 430 | println("Cat is sleeping on its owner's bed") 431 | } 432 | } 433 | 434 | class Bird: Animal, FlyingAnimal{ 435 | override fun eat() { 436 | println("Bird is eating forage") 437 | } 438 | 439 | override fun sleep() { 440 | println("Bird is sleeping in the nest") 441 | } 442 | 443 | override fun fly() { 444 | println("Bird is flying so high") 445 | } 446 | } 447 | ``` 448 | Note: If we would like to we can implement Animal interface in FlyingAnimal interface. So, we won't need to implement two interfaces for classes which animals can fly such as Bird. 449 | 450 | ## Dependency Inversion Principle 451 | Dependency Inversion Principle tells us about the coupling between the different classes or modules.
452 | Higher level classes should not be dependent to lower level classes. Both should be dependent to abstractions. It is based on removing the dependency with the interface.
453 | The dependence of a class or method on other classes that use it should be minimized. Changes made in the child classes should not affect parent classes.

454 | Let's think that we need to develop a mobile application for both Android and iOS. To do that, we need an Android Developer and an iOS Developer. These classes will have a method to develop a mobile application by using their own platform and programming language. 455 | ```kotlin 456 | class AndroidDeveloper{ 457 | fun developMobileApp(){ 458 | println("Developing Android Application by using Kotlin") 459 | } 460 | } 461 | 462 | class IosDeveloper{ 463 | fun developMobileApp(){ 464 | println("Developing iOS Application by using Swift") 465 | } 466 | } 467 | 468 | fun main(){ 469 | val androidDeveloper = AndroidDeveloper() 470 | val iosDeveloper = IosDeveloper() 471 | 472 | androidDeveloper.developMobileApp() 473 | iosDeveloper.developMobileApp() 474 | } 475 | ``` 476 | To fix the problem in here, we can create an interface called as MobileDeveloper. AndroidDeveloper and IosDeveloper classes with implement this interface.
477 | If we want to store some different datas for each developer type, we can use this principle. Also, maybe we want to separate mobile services for Android Developers. To do that, we can create different methods for Android Developer but developing mobile application will be same for both Android and iOS developers. So, we should have an interface for same operations. 478 | ```kotlin 479 | interface MobileDeveloper{ 480 | fun developMobileApp() 481 | } 482 | 483 | class AndroidDeveloper(var mobileService: MobileServices): MobileDeveloper{ 484 | override fun developMobileApp(){ 485 | println("Developing Android Application by using Kotlin. " + 486 | "Application will work with ${mobileService.serviceName}") 487 | } 488 | enum class MobileServices(var serviceName: String){ 489 | HMS("Huawei Mobile Services"), 490 | GMS("Google Mobile Services"), 491 | BOTH("Huawei Mobile Services and Google Mobile Services") 492 | } 493 | } 494 | 495 | class IosDeveloper: MobileDeveloper{ 496 | override fun developMobileApp(){ 497 | println("Developing iOS Application by using Swift") 498 | } 499 | } 500 | 501 | fun main(){ 502 | val developers = arrayListOf(AndroidDeveloper(AndroidDeveloper.MobileServices.HMS), IosDeveloper()) 503 | developers.forEach { developer -> 504 | developer.developMobileApp() 505 | } 506 | } 507 | ``` 508 | 509 | # Design Patterns 510 | Design patterns can speed up our software development process because they provide tested, proven development paradigms.
511 | Design patterns are solutions to common problems that software developers encounter during software development process. These solutions have been achieved through trial and error by numerous software developers over a long period of time. Then, they gave names to these solutions which they found for certain problems.

512 | Design patterns are categorized in 3 groups. These are; Creational Design Patterns, Structural Design Patterns and Behavioral Design Patterns
513 | I will explain each design patterns of these categories and give examples for them to improve the knowledge with practice. 514 | 515 | ## Creational Design Patterns 516 | Creational design patterns are dealing with object creation situation and trying to create objects which will be suitable to situation. Creating objects can cause the some complexity. Creational design patterns solve this problem by managing the object creation situation. 517 | 518 | ### Singleton Pattern 519 | Singleton is one of the creational design pattern that lets us to create one instance of the class and provide a global access point to this instance.
520 | For singleton, we should define all constructors as private. Then, we should define one static instance of the class which will hold existing instance or will create new one.

521 | Applying singleton pattern is so easy in Kotlin. But first, I want to give an example in Java to make it more understandable. 522 | ```java 523 | public class SingletonMainClass { 524 | public static void main(String[] args) { 525 | SingletonPattern singletonPattern = SingletonPattern.getInstance(); 526 | singletonPattern.writeHelloWorld(); 527 | } 528 | } 529 | class SingletonPattern { 530 | private static SingletonPattern singletonPattern; 531 | private static Object synchronizedObject = new Object(); 532 | 533 | private SingletonPattern() { } 534 | 535 | public static SingletonPattern getInstance() { 536 | if (singletonPattern == null) { 537 | synchronized (SingletonPattern.class) { 538 | if (singletonPattern == null) { 539 | singletonPattern = new SingletonPattern(); 540 | } 541 | } 542 | } 543 | return singletonPattern; 544 | } 545 | 546 | public void writeHelloWorld() { 547 | System.out.println("Hello world!"); 548 | } 549 | } 550 | ``` 551 | As you see above, there are so much works when we want to implement Singleton Pattern design pattern to our classes that we need to do.
552 | Unlike Java, Kotlin provides so easy feature for this. This feature is called as object. When we define classes as object, this object will be singleton automatically. 553 | ```kotlin 554 | fun main() { 555 | SingletonPattern.writeHelloWorld() 556 | } 557 | 558 | object SingletonPattern { 559 | fun writeHelloWorld() { 560 | println("Hello World!") 561 | } 562 | } 563 | ``` 564 | 565 | ### Factory Method Pattern 566 | Factory Method is one of the creational design pattern which provides us an interface to create objects. It allows subclasses to change the type of objects that will be created by the interface which we have created before.
567 | Briefly, we use Factory Method Pattern when we don't know which subclasses we will need to create in the future.
568 | 569 | Let me give you an example. While developing Android applications, just a few years ago, we have been using only Google Mobile Services. Then, Huawei have been created their own mobile services which has been called as Huawei Mobile Services.
570 | This situation has brought a new challenge for mobile developers which is about managing two different mobile services while developing Android applications.
571 | 572 | Let's think about an idea that mobile services will show the map on screen and will authenticate the user. First, we need to create an interface called as MobileService. 573 | ```kotlin 574 | interface MobileService { 575 | fun authenticateUser() 576 | fun showMap() 577 | } 578 | ``` 579 | Now, we need to create real mobile services which will implement our MobileService interface. For that, I have created two class which are called as HuaweiMobileServices and GoogleMobileServices.
580 | These mobile services are doing similar operations but in different ways. For example, Huawei authenticate users with Huawei ID and Google authenticate users with Gmail. And Huawei is using Petal Maps for navigation and Google is using Google Maps. 581 | ```kotlin 582 | class HuaweiMobileServices: MobileService { 583 | override fun authenticateUser() { 584 | println("User has been authenticated with Huawei ID") 585 | } 586 | 587 | override fun showMap() { 588 | println("Petal Maps has been started for navigation") 589 | } 590 | } 591 | 592 | class GoogleMobileServices: MobileService { 593 | override fun authenticateUser() { 594 | println("User has been authenticated with Gmail") 595 | } 596 | 597 | override fun showMap() { 598 | println("Google Maps has been started for navigation") 599 | } 600 | } 601 | ``` 602 | Now, all we need to do is creating Factory for these mobile service classes which we have implemented from MobileService interface.
603 | We can send any different data to separate different type of mobile services. It can be like String, Integer or some Enum values.
604 | 605 | I will explain by doing with Enum. 606 | ```kotlin 607 | class MobileServiceFactory(){ 608 | fun getMobileService(mobileServiceType: MobileServiceType): MobileService { 609 | return when(mobileServiceType) { 610 | MobileServiceType.HUAWEI -> HuaweiMobileServices() 611 | MobileServiceType.GOOGLE -> GoogleMobileServices() 612 | } 613 | } 614 | } 615 | 616 | enum class MobileServiceType(){ 617 | HUAWEI, 618 | GOOGLE 619 | } 620 | ``` 621 | Now, let's test it on main method and see the output to understand what we did above: 622 | ```kotlin 623 | fun main() { 624 | var mobileService = MobileServiceFactory() 625 | val hms = mobileService.getMobileService(MobileServiceType.HUAWEI) 626 | val gms = mobileService.getMobileService(MobileServiceType.GOOGLE) 627 | 628 | println("Huawei:") 629 | hms.apply { 630 | authenticateUser() 631 | showMap() 632 | } 633 | println("Google:") 634 | gms.apply { 635 | authenticateUser() 636 | showMap() 637 | } 638 | } 639 | ``` 640 | Output 641 | ``` 642 | Huawei: 643 | User has been authenticated with Huawei ID 644 | Petal Maps has been started for navigation 645 | Google: 646 | User has been authenticated with Gmail 647 | Google Maps has been started for navigation 648 | ``` 649 | 650 | ### Abstract Factory Pattern 651 | Abstract Factory Pattern is another creational pattern which is similar to Factory Method Pattern. The main difference is, Abstract Factory Pattern creates factories which will create other factories.
652 | 653 | Abstract Factory Pattern lets us to create objects which are families with each other. The main idea in here is, Abstract Factory Pattern don't want our objects to be depend on the concrete classes. Because we might not know what will happen with these classes in the future and depends on the future requirements of the project we might want to allow extensibility.
654 | 655 | Let's imagine that we will create UI classes for website and these UI classes will be different for desktop users and mobile device users. To do that, we will have different products for different UI objects such as Button, ImageView, TextView, EditText, Dialog and etc.
656 | And also, these UI objects will be different for desktop and mobile users. Abstract Factory can help us in this scenario.
657 | 658 | For example, let's think that dialog and imageview will be different on desktop and mobile device.
659 | First, we will define a dialog interface and each device type will implement this interface. 660 | ```kotlin 661 | interface Dialog { 662 | fun showPopupDialog() 663 | } 664 | class DesktopDialog: Dialog { 665 | override fun showPopupDialog() { 666 | println("Desktop dialog will be shown") 667 | } 668 | } 669 | class MobileDeviceDialog: Dialog { 670 | override fun showPopupDialog() { 671 | println("Mobile device dialog will be shown") 672 | } 673 | } 674 | ``` 675 | Then, we will create an interface for our second UI object which is ImageView.
676 | Let's make some difference in here. For example, users will be able to see image bigger when they click to image on desktop. But, users will not be able to see image bigger on mobile device and nothing will happen when users click on image. 677 | ```kotlin 678 | interface ImageView { 679 | fun showImage() 680 | } 681 | class DesktopImageView: ImageView { 682 | override fun showImage() { 683 | println("Image will be shown on desktop and will be clickable.") 684 | } 685 | } 686 | class MobileDeviceImageView: ImageView { 687 | override fun showImage() { 688 | println("Image will be shown on mobile device and nothing will happen when user click on image.") 689 | } 690 | } 691 | ``` 692 | Now, all we need to do is focusing on creating factories. 693 | ```kotlin 694 | interface UIFactory{ 695 | fun createDialog(): Dialog 696 | fun createImageView(): ImageView 697 | } 698 | ``` 699 | Then, we need to create a factory class for each device type and these factory classes will implement the main UIFactory class for creating UI objects. 700 | ```kotlin 701 | class DesktopUIFactory: UIFactory { 702 | override fun createDialog(): Dialog = DesktopDialog() 703 | override fun createImageView(): ImageView = DesktopImageView() 704 | } 705 | class MobileDeviceUIFactory: UIFactory { 706 | override fun createDialog(): Dialog = MobileDeviceDialog() 707 | override fun createImageView(): ImageView = MobileDeviceImageView() 708 | } 709 | ``` 710 | Now, we will create a base class called as Device. And this device will be created depends on the device type such as desktop or mobile device. 711 | ```kotlin 712 | class Device(uiFactory: UIFactory) { 713 | var dialog: Dialog = uiFactory.createDialog() 714 | var imageView: ImageView = uiFactory.createImageView() 715 | } 716 | ``` 717 | For now, we need to create an enum class to getting device type easily. 718 | ```kotlin 719 | enum class DeviceType{ 720 | MOBILE, 721 | DESKTOP 722 | } 723 | ``` 724 | Now, we will test all things which we did. First test will be for mobile device. 725 | ```kotlin 726 | fun main() { 727 | lateinit var uiFactory: UIFactory 728 | 729 | var deviceType = DeviceType.MOBILE 730 | uiFactory = when (deviceType) { 731 | DeviceType.MOBILE -> { 732 | MobileDeviceUIFactory() 733 | } 734 | DeviceType.DESKTOP -> { 735 | DesktopUIFactory() 736 | } 737 | } 738 | var device: Device = Device(uiFactory) 739 | 740 | device.apply { 741 | dialog.showPopupDialog() 742 | imageView.showImage() 743 | } 744 | } 745 | ``` 746 | Output 747 | ``` 748 | Mobile device dialog will be shown 749 | Image will be shown on mobile device and nothing will happen when user click on image. 750 | ``` 751 | Now, just change the device type as Desktop on main method. 752 | ```kotlin 753 | var deviceType = DeviceType.DESKTOP 754 | ``` 755 | Output 756 | ``` 757 | Desktop dialog will be shown 758 | Image will be shown on desktop and will be clickable. 759 | ``` 760 | 761 | ### Builder Pattern 762 | Builder Pattern is a creational design pattern which allows us to construct complex objects. While creating objects with Builder Pattern, we can create different types and representations of objects which are using the same builder code.

763 | With the Builder Pattern, we do not get all data which we will need in the class on constructor method. Instead of getting data on constructor method, we are getting all inputs step by step in separated setter methods with inner class which is called as Builder.

764 | Let's examine Builder Pattern with a simple example.
765 | Let's imagine that we want to create a dialog to show on screen. This dialog will have title, icon, message, positive button and negative button. Builder pattern is good pattern to develop a class for this problem.

766 | First of all, we are defining private constructor because we don't want to set values directly with Dialog class.
767 | Then we define a Builder class to build our object. Fields' setter methods will private. Thus, we will only set them with the methods which we have created.
768 | With the build method, we are creating Dialog class according to the values which we have defined. 769 | ```kotlin 770 | class Dialog private constructor( 771 | private val title: String?, 772 | private val message: String?, 773 | private val icon: String?, 774 | private val positiveButtonText: String?, 775 | private val negativeButtonText: String?) 776 | { 777 | fun showDialog() { 778 | println("Title: $title\n" + 779 | "Message: $message\n" + 780 | "Icon: $icon\n" + 781 | "Positive Button Text: $positiveButtonText\n" + 782 | "Negative Button Text: $negativeButtonText") 783 | } 784 | 785 | class Builder { 786 | var title: String = "" 787 | private set 788 | var message: String = "" 789 | private set 790 | var icon: String = "" 791 | private set 792 | var positiveButtonText: String = "" 793 | private set 794 | var negativeButtonText: String = "" 795 | private set 796 | 797 | fun setTitle(title: String) = apply { this.title = title } 798 | fun setMessage(message: String) = apply { this.message = message } 799 | fun setIcon(icon: String) = apply { this.icon = icon } 800 | fun setPositiveButtonText(positiveButtonText: String) = apply { this.positiveButtonText = positiveButtonText } 801 | fun setNegativeButtonText(negativeButtonText: String) = apply { this.negativeButtonText = negativeButtonText } 802 | 803 | fun build() = Dialog(title, message, icon, positiveButtonText, negativeButtonText) 804 | } 805 | } 806 | 807 | fun main() { 808 | val dialog = Dialog.Builder() 809 | .setTitle("Exit") 810 | .setMessage("Are you sure that you want to leave the app?") 811 | .setIcon("Exit image") 812 | .setPositiveButtonText("Yes") 813 | .setNegativeButtonText("No") 814 | .build() 815 | dialog.showDialog() 816 | } 817 | ``` 818 | 819 | ### Prototype Pattern 820 | Prototype Patterns is a creational design pattern which allows us to create copies of existing objects. We can use prototype pattern when we want to create copies of existing objects and don't want them to be dependent on their classes.
821 | Note: We can even copy private variables or methods while using prototype pattern because we are cloning objects.

822 | When object has so much parameters on the constructor method, it can cost too much while creating new objects from the existing class. With the help of Prototype Pattern, we can copy the existing objects without using "new" keyword.
823 | That means, Prototype Pattern is very useful when we want to create similar objects from existing class.
824 | It can help us to save so much time while creating copied objects of existing classes.

825 | Let's examine Prototype Pattern with a simple example.
826 | Using Prototype Pattern in Kotlin is so easy. I will give you an example about mobile phones.

827 | Let's imagine that we have a data class which is called as MobilePhone. This data class will have 5 fields. These fields are phone brand as String, model name as String, operating system name as String and size of RAM as Int.
828 | ```kotlin 829 | data class MobilePhone( 830 | val phoneBrand: String, 831 | val modelName: String, 832 | val operatingSystemName: String, 833 | val sizeOfRAM: Int 834 | ) 835 | ``` 836 | Now, we will add a function to data class which is called as printPhoneDetails. This function will print the features of the phone. 837 | ```kotlin 838 | data class MobilePhone( 839 | val phoneBrand: String, 840 | val modelName: String, 841 | val operatingSystemName: String, 842 | val sizeOfRAM: Int 843 | ) { 844 | fun printPhoneDetails() { 845 | println("$phoneBrand $modelName has $sizeOfRAM GB RAM and runs with $operatingSystemName operating system") 846 | } 847 | } 848 | ``` 849 | On the above, we have very simple data class to describe Prototype Pattern.
850 | First, we will create one object which is P40 Lite. Then, we will use printPhoneDetails function to print phone details and, we will see the output.
851 | ```kotlin 852 | fun main() { 853 | val p40Lite = MobilePhone( 854 | "Huawei", 855 | "P40 Lite", 856 | "Android", 857 | 6, 858 | 859 | ) 860 | p40Lite.printPhoneDetails() 861 | } 862 | ``` 863 | Output 864 | ``` 865 | Huawei P40 Lite has 6 GB RAM and runs with Android operating system 866 | ``` 867 | In Kotlin, we don't need to clone objects by hand if they are model as data class. This makes everything so easy in Kotlin to copy objects of data classes.

868 | Let's think that Huawei will introduce a new mobile phone which is P50 Pro. For this phone, model name will be changed. Size of RAM will increase and operating system will be changed to Harmony OS which is the new operating system developing by Huawei.
869 | If we want other functions to stay same for all mobile phones, we can just copy and change variables of the class. Other functions can be like buyThePhone, addToShoppingCart and many more according to project which we are developing. In this example, I just developed one function called as printPhoneDetails to print details of the phone.

870 | You may ask why we just don't create new object. We can have more fields for the class such as camera details, processor, size of the phone, screen details. In this type of object, many fields can be same for many different mobile phone. If we create same fields as same again and again, this can cost too much to develop all these objects, especially when we have hundreds of phones.
871 | In this example, phoneBrand will be same for both of the objects. 872 | ```kotlin 873 | fun main() { 874 | val p40Lite = MobilePhone( 875 | "Huawei", 876 | "P40 Lite", 877 | "Android", 878 | 6, 879 | 880 | ) 881 | p40Lite.printPhoneDetails() 882 | 883 | val p50Pro = p40Lite.copy( 884 | modelName = "P50 Pro", 885 | operatingSystemName = "Harmony", 886 | sizeOfRAM = 8 887 | ) 888 | p50Pro.printPhoneDetails() 889 | } 890 | ``` 891 | Output 892 | ``` 893 | Huawei P40 Lite has 6 GB RAM and runs with Android operating system 894 | Huawei P50 Pro has 8 GB RAM and runs with Harmony operating system 895 | ``` 896 | As we see, we have copied P50 Pro from P40 Lite and just changed the fields which need to be changed. When fields should be same, we don't need to define them as we do in constructor methods. 897 | 898 | ## Structural Design Patterns 899 | Structural design patterns are dealing about how classes and objects will be in a relationship with each other in structurally. Structural design patterns simplify the design when we are going to have huge object structures in our project. It helps us to create objects and classes without repeating themselves. 900 | 901 | 902 | # License 903 | ``` 904 | Copyright 2021 Berk Berber 905 | 906 | Licensed under the Apache License, Version 2.0 (the "License"); 907 | you may not use this file except in compliance with the License. 908 | You may obtain a copy of the License at 909 | 910 | http://www.apache.org/licenses/LICENSE-2.0 911 | 912 | Unless required by applicable law or agreed to in writing, software 913 | distributed under the License is distributed on an "AS IS" BASIS, 914 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 915 | See the License for the specific language governing permissions and 916 | limitations under the License. 917 | 918 | ``` 919 | See more details: LICENSE 920 | --------------------------------------------------------------------------------