<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Farnoosh Varmazyar on Medium]]></title>
        <description><![CDATA[Stories by Farnoosh Varmazyar on Medium]]></description>
        <link>https://medium.com/@f.varmazyar992?source=rss-628b4df4962d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nc-i7llWYqFNZc6jcQCg4w.jpeg</url>
            <title>Stories by Farnoosh Varmazyar on Medium</title>
            <link>https://medium.com/@f.varmazyar992?source=rss-628b4df4962d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:26:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@f.varmazyar992/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Everything about cryptography that programmers need to know]]></title>
            <link>https://medium.com/@f.varmazyar992/everything-about-cryptography-that-programmers-need-to-know-360322a8729c?source=rss-628b4df4962d------2</link>
            <guid isPermaLink="false">https://medium.com/p/360322a8729c</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programmering]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Farnoosh Varmazyar]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 12:10:56 GMT</pubDate>
            <atom:updated>2023-11-04T10:32:20.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*GZgSCXT1kxQCLPYt1QPQSw.jpeg" /></figure><h3>What is cryptography ?</h3><p>Cryptography is a branch of mathematical science that tries to convert an understandable message into a message that only the sender and receiver can understand..</p><p><strong><em>What is the purpose of cryptography ?</em></strong></p><ul><li><strong><em>Confidentiality </em></strong>: The confidentiality of the message is important</li><li><strong><em>Authentication </em></strong>: The identity and authenticity of the message is important</li></ul><h3>Basic concepts</h3><ul><li><strong><em>Plaintext </em></strong>: the original intelligible message</li><li><strong><em>Cipher</em></strong> : an algorithm to convert an intelligible message into an unintelligible message</li><li><strong><em>Ciphertext</em></strong> : the transformed message</li><li><strong><em>Key</em></strong> : an important tool in cryptography that only the sender and receiver know</li></ul><p>In the following, its concepts and application will be specified.</p><h3>Type of Algorithms</h3><h4><strong>Hashing</strong></h4><p><strong><em>Types of Hashing</em></strong></p><ul><li><em>MD5(banned) /128bit</em><br> MD5 is considered broken (since 2012). The first hash collisions where found in 2004. So its security has been severely compromised.</li><li><em>SHA0/SHA1(banned 2014)/160bit</em><br> In 2005, researchers demonstrated a collision attack against SHA1 that showed it was possible to create two distinct input messages that produced the same hash value.</li><li><em>SHA-256</em></li><li><em>SHA-384</em></li><li><em>SHA-512</em></li><li><em>SHA3</em></li></ul><p><strong><em>What is Hashing and how does it work?</em></strong><br> Hashing is a one-way function and for each unique input we have a unique output.<br> When a hash algorithm produces the same hash value for two different input values it is called hash collision.<br> Hashing is a key-less algorithm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*L8IomSpbKQ8TnO_5UDi6yQ.png" /></figure><p><strong><em>What happen if use MD5 or SHA1 for encryption?</em></strong><br> The biggest threat occurs in the security of the server that hashes the user’s password and then stores it in the database, which is completely wrong. Because the mentioned functions have collision<br> If you need encryption via hash functions, never use SHA0, SHA1 and MD5.</p><h4><strong>HMAC</strong></h4><p><strong><em>Type of HMAC</em></strong></p><ul><li><em>HMACSHA-256</em></li><li><em>HMACSHA-512</em></li><li><em>HMACMD5</em></li></ul><p><strong><em>What is HMAC and how does it work?</em></strong><br> HMAC (Hash-based Message Authentication Code) is a type of keyed hash algorithm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*D39WsU7_-G5Ve-Lwnm2jhA.png" /></figure><p>The algorithm works like this, to ensure that the message is not manipulated between exchanges, the client side creates a MAC by the key and the HMAC algorithm, and the receiver side repeats this, if the MAC is same, the message is authentic.<br> Both sides need the same key to generate the same Mac</p><p><strong><em>What is the application of this algorithm in programming?</em></strong><br> Imagine that you are developing an application in the field of financial payments. In this application, you are supposed to send a financial transaction including source, destination and amount to the server.</p><p><strong><em>If a Man-in-the-Middle attack occurs in transit and the hacker changes the destination, how can the server notice the change?</em></strong><br> In the field of financial payments, message <strong><em>authenticity</em></strong> has a higher priority than confidentiality. Therefore, HMAC is an ideal algorithm for message authentication. The method of checking the authenticity of the message as shown in the above picture is that the client send the plaintext and MAC to the server ,and the server creates a MAC with plaintext and HMAC algorithm. Now it check the generated MAC with the sent MAC, if they are the same, the message is valid</p><p><strong><em>What happen if attacker change the plaintext?</em></strong><br> Because it doesn’t have a key (the key must be secret between the client and the server), it doesn’t have the ability to generate a MAC, so the server will recognize it as fake and reject it.</p><h4><strong>Symmetric</strong></h4><p><strong><em>Type of symmetric</em></strong></p><ul><li><em>RC4(unsafe)</em></li><li><em>DES(unsafe) : 56-bit Key</em></li><li><em>3DES : 64/112/168 bit Key</em></li><li><em>AES (Rijndael) :128/192/256 bit Key</em></li></ul><p><strong><em>What is symmetric and how does it work?</em></strong><br> These are symmetric algorithms where the communication parties need a share key for encryption and decryption. These types of algorithms maintain <strong><em>confidentiality</em></strong>. A symmetric algorithm actually encrypts part of the data, that is, when we say that the key length is 128 bits, it can actually encrypt or decrypt 128 bits of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQ181hdcC_SBBShYB4F0Lw.png" /></figure><p>We actually have two types of symmetric</p><ol><li><strong><em>Block cipher </em></strong>: It encrypts and decrypts data block by block</li><li><strong><em>stream cipher</em> </strong>: It encrypts and decrypts a data stream</li></ol><p><strong><em>Block Cipher vs. Stream Cipher </em></strong><br> Block ciphers have good speed if your data length is clear. In this case, you can use <strong><em>AES </em></strong>or <strong><em>3DES,</em></strong> each of which has <em>ECB</em> and <em>CBC</em> modes of operation, which will be discussed later.</p><p>If you have streams or the data size is very varied, using block ciphers is very inefficient in terms of performance, as you have to break the data into blocks, which degrades the performance of the stream. So you should use stream cipher so that the performance does not decrease. In this case, you can use the <strong><em>RC4</em></strong> algorithm, but <strong><em>RC4</em></strong> is insecure in addition to being old, which is not recommended at all. On the other hand, we have a powerful stream cipher called <strong><em>AES-GCM</em></strong> that you can always use</p><p><strong><em>Block Cipher modes of Operation</em></strong></p><ul><li><strong><em>ECB (Electronic Code Book)</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9QaqYywX6IADh5bvJpnO6A.png" /></figure><p><strong><em>How does it work?</em></strong><br> Imagine we have a 1 KB plaintext that needs to be encrypted with a 128-bit block size with ECB mode.<br> The plaintext is divided into 8 blocks and each of these blocks is encrypted separately (decrypted in the same way at the destination).<br> This mode is not safe because we have information leakage .Because ECB encrypts identical plaintext blocks into identical ciphertext blocks, it does not hide data patterns well. ECB is not recommended for use in cryptographic protocols.</p><ul><li><strong><em>CBC (Cipher Block Chaining)</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-bpTSBdwVT1yyWP5-L1kFQ.png" /></figure><p><strong><em>How does it work?</em></strong><br> For better understanding, first let’s see the below image on how XOR works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*4qxnCEAVB30yi-EsfK-fuQ.gif" /></figure><p>In this method, the output of each block is transferred to the next block and the XOR operator is applied to it.<br> This operating mode is more secure than the ECB mode, but recently attacks such as Oracle Padding occurred, which caused information leakage (Explaining this attack and securing this mod against such attacks is beyond the scope of this article).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*VMjucTtPHHN06ww37qsRvg.jpeg" /><figcaption>CBC is more secure than ECB</figcaption></figure><p><strong><em>What is the application of this algorithm in programming?</em></strong><br> Let’s imagine that we are going to create a mobile application that is supposed to receive data via a server as a stream (like a movie) and <strong><em>confidentiality </em></strong>is required to avoid copyright. Symmetric algorithms are very suitable for maintaining confidentiality.</p><blockquote>Note: If you need symmetric cryptography somewhere, use <strong><em>AES </em></strong>(<strong><em>AES-GCM</em></strong>) and this algorithm with a key length of 128 bits is sufficient for most cases. This algorithm is not used at all with a key length of 192 bits. With a key length of 256 bits, it is a waste of resources.</blockquote><p><strong>☕️ Grab a cup of coffee and keep going.</strong></p><h4><strong>Asymmetric</strong></h4><p><strong><em>Type of asymmetric</em></strong></p><ul><li><em>Ed448 signing</em></li><li><em>X448 key exchange</em></li><li><em>ECC(Elliptic curve cryptography)</em></li><li><em>RSA</em></li><li><em>Diffie-Hellman key exchange</em></li><li><em>DSA</em></li><li><em>Key Serialization</em></li><li><em>Asymmetric Utilities</em></li></ul><p><strong><em>What is asymmetric cryptography and how does it work?</em></strong><br> The basis of asymmetric algorithms is that a pair of private and public keys is mathematically generated, and if you have the private key, you can access the public key, but the opposite is not true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*GGMJgr5yyCnFgBlaaHU6TQ.png" /></figure><p>The most famous algorithms in this category are ECC, RSA and Diffie-Hellman.</p><p><strong><em>What is the application of this algorithm in programming?</em></strong><br> Suppose you work in an insecure environment and you need others to send you information, but only you can decrypt it, that mean, the person who encrypts the information through the public key and sends it to you cannot decrypt it.<br> In this method, the private key belongs to the person who is going to open the messages with it, but the public key may be available to many.<br> Like when the public key is provided to the client through the server and this key must be hardcoded in the application</p><h4><strong>Random Number Generation</strong></h4><p><strong><em>What is Random number generation and how does it work?</em></strong><br> Every system has an entropy, this indicator is very important in cryptography.<br> Entropy is the cornerstone of cryptography as it is used to generate session keys. The more random the numbers, the more secure the cryptographic system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*vmf8AaaKLm_hZmUbegFGOw.png" /></figure><p>In Linux, we have two types of random number generators , one is <strong><em>Dev</em></strong> <strong><em>Random </em></strong>and the other is <strong><em>Dev Urandom</em></strong>.<br> The <strong><em>Urandom</em></strong> is used when there is a constant need for random numbers and its randomness is not much important.<br> The <strong><em>Random</em></strong> generates a random number based on the entropy of the system, i.e. if the entropy level is low, it blocks the task until the entropy level increases.<br> the <strong><em>Random</em></strong> is suitable for tasks where security is a prime concern as it will block the reads if the randomness is not up to the mark.<br> Since Android is based on Linux, Android always checks the entropy level to generate a secure random number.</p><p><strong><em>What is the application of this algorithm in programming?</em></strong><br> To better understand the use of secure random numbers, let me give an example. Imagine you are a Java developer and you want to send a number as an OTP to a client .<br> If you use the <em>Random</em> class to generate a random number. The number you generate is not secure and the numbers generated by this class are for statistical use only<br> If you really want to generate a secure random number that is not predictable (predictable meaning that it cannot be broken mathematically, and the sequence cannot be easily determined), use the <em>SecureRandom </em>class in Java.</p><h3>Common mistakes</h3><p>let’s talk about common mistakes in cryptography</p><ul><li><strong>Rolling your own cryptographic algorithms and implementations</strong><br>A common mistake is to write your own algorithm. For example, combining two algorithms with a specific order. This is not recommended at all.<br> All algorithms should be standard and open source.</li><li><strong>Poor key management </strong><br>Key management is very important because the validity of our operations depends on the key. If the key is stolen, the cryptography system we have implemented will lose its effectiveness</li><li><strong>Failure to centralize cryptography</strong><br> manage each part of the program in a specific way and do not use a centralized approach</li><li><strong>Randomness that is not random</strong></li></ul><p><em>Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=360322a8729c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Design Patterns : Factory Method]]></title>
            <link>https://medium.com/@f.varmazyar992/android-design-patterns-factory-method-519c713ad604?source=rss-628b4df4962d------2</link>
            <guid isPermaLink="false">https://medium.com/p/519c713ad604</guid>
            <category><![CDATA[factory-method-pattern]]></category>
            <category><![CDATA[creational-patterns]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-developers]]></category>
            <dc:creator><![CDATA[Farnoosh Varmazyar]]></dc:creator>
            <pubDate>Fri, 20 Aug 2021 20:12:03 GMT</pubDate>
            <atom:updated>2022-04-25T16:20:30.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creational Design Patterns in Android : Factory Method</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*MGMIa0dTag3I5ZXGyIXdxA.jpeg" /></figure><h4>Introduction <strong>Factory Method</strong> Design Pattern</h4><p>Factory Method design pattern is a creational design pattern which talks about the creation of an object.The Factory Method pattern says that define an interface ( A java interface or an abstract class) and let the subclasses decide which object to instantiate. In other words, subclasses are responsible to create the instance of the class.</p><p>The Factory Method pattern suggests that you replace direct object construction calls with calls to a special <em>factory</em> method.</p><h4>When to use Factory Method pattern?</h4><ul><li><strong><em>When a class doesn’t know what sub-classes will be required to create.</em></strong></li><li><strong><em>When a class wants that its sub-classes specify the objects to be created.</em></strong></li></ul><h4>Implementation of Factory Method pattern :</h4><p>For better understanding the Factory Method pattern, let’s solve an example.</p><p>Imagine we are going to create a calorie counter app for Android that is calculate the calories of desserts like apple pie , fried ice cream and cheesecake.</p><ul><li>Complete the interface as follows:</li></ul><pre> interface Dessert <br> {<br>    fun name(): String?<br>    fun calories(): String?<br> }</pre><ul><li>Create concrete classes of <em>Desser</em>t, like so:</li></ul><pre>  class ApplePie :Dessert<br>  {<br>     override fun name(): String?<br>     {<br>       return &quot;Apple Pie&quot;<br>     }<br>     override fun calories(): String?<br>     {<br>       return &quot;237 kcal &quot;<br>     }<br>  }<br></pre><pre>  class Cheesecake :Dessert <br>  {<br>     override fun name(): String?<br>     {<br>       return &quot;Cheesecake&quot;<br>     }<br>     override fun calories(): String?<br>     {<br>       return &quot;321 kcal&quot;<br>     }<br>  }<br></pre><pre>  class FriedIceCream :Dessert <br>  {<br>     override fun name(): String?<br>     {<br>       return &quot;Fried ice cream&quot;<br>     }<br>     override fun calories(): String?<br>     {<br>       return &quot;273 kcal&quot;<br>     }<br>  }</pre><ul><li>create an enum class called <em>DessertType</em></li></ul><pre>  enum class DessertType<br>  {<br>     <em>ApplePie</em>,<br>     <em>Cheesecake</em>,<br>     <em>FriedIceCream<br>  </em>}</pre><ul><li>Next, create a new class called <em>DessertFactory </em>that looks like this:</li></ul><pre>  class DessertFactory <br>  {<br>     fun getDesert(desertType: DessertType) :Dessert <br>     {<br>        when (desertType) <br>        {<br>            DessertType.<em>ApplePie </em>-&gt; <br>            {<br>              return ApplePie()<br>            }</pre><pre>            DessertType.<em>Cheesecake </em>-&gt; <br>            {<br>              return Cheesecake()<br>            }</pre><pre>            DessertType.<em>FriedIceCream </em>-&gt; <br>            {<br>              return FriedIceCream()<br>            }<br>        }<br>     }<br>  }</pre><ul><li>Open the activity_main.xml file and add this :</li></ul><pre> &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:gravity=&quot;center&quot;&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/text_bread&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_weight=&quot;1&quot;<br>            android:gravity=&quot;center&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/text_calories&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_weight=&quot;1&quot;<br>            android:gravity=&quot;center&quot; /&gt;</pre><pre> &lt;/LinearLayout&gt;</pre><ul><li>Open the MainActivity.java file and edit the onCreate() method to match the following code:</li></ul><pre>class MainActivity : AppCompatActivity() <br>{<br>    override fun onCreate(savedInstanceState: Bundle?)  <br>    {<br>      super.onCreate(savedInstanceState)<br>      setContentView(R.layout.<em>activity_main</em>)<br>     <br>      val textBread = findViewById&lt;View&gt;(R.id.<em>text_bread</em>)  <br>      val textCalories = findViewById&lt;View&gt;(R.id.<em>text_calories</em>) </pre><pre>      val desertFactory = DessertFactory()<br>      val desert = desertFactory.getDesert(DessertType.<em>ApplePie</em>)</pre><pre>      textBread.setText(desert.name())<br>      textCalories.setText<em>t </em>(desert.calories())           <br>         <br>    }<br>}</pre><p><em>Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=519c713ad604" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Design Patterns : Builder]]></title>
            <link>https://medium.com/@f.varmazyar992/android-design-patterns-builder-21227ac392e5?source=rss-628b4df4962d------2</link>
            <guid isPermaLink="false">https://medium.com/p/21227ac392e5</guid>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Farnoosh Varmazyar]]></dc:creator>
            <pubDate>Sat, 14 Aug 2021 09:42:19 GMT</pubDate>
            <atom:updated>2021-08-21T10:47:30.097Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creational Design Patterns in Android: Builder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Kh1Sv0gABvkgplz0Myu8_w.jpeg" /></figure><h4><strong>Introduction Builder Design Pattern</strong></h4><p>Builder design pattern is categorized under Creational Design Patterns. Builder pattern aims to <em>“Separate the construction of a complex object from its representation so that the same construction process can create different representations.</em>” In other words the pattern allows you to produce different types and representations of an object using the same construction code.</p><h4>In the Real World</h4><p>The simplest real world example of the builder pattern, which most of us are familiar with, is when we make (or order) a pizza. The pizza toppings cannot be added in any random order. Instead, there is a step-by-step process that is followed. This usually begins by deciding on the size of the pizza, and therefore how much dough to use. Then the sauce is added, then cheese, then maybe some pepperoni and some olives, and so forth. Yet, as any pizza-maker will tell you, not all orders are the same, and therefore, not all pizzas are built in the same way. Each step in the process, and each topping that is added, can be thought of as a single step in the much larger builder pattern that is used to make.</p><h4><strong>When </strong>to use Builder pattern<strong> ?</strong></h4><ul><li><strong><em>Use the Builder pattern to get rid of a “telescopic constructor” </em></strong><em>.</em></li></ul><p>Imagine you have a constructor with ten optional parameters. Work with such a constructor is very difficult. Therefore, you overload the builder and create several shorter versions with fewer parameters. These structures still point to the principle and pass the default values to each deleted parameter.</p><pre>class Pizza {<br>    Pizza(int size) { ... }<br>    Pizza(int size, boolean cheese) { ... }<br>    Pizza(int size, boolean cheese, boolean pepperoni) { ... }<br>    // ...</pre><p>The Builder pattern lets you build objects step by step, using only those steps that you really need.</p><ul><li><strong><em>Use the Builder pattern when you want your code to be able to create different representations of some product.</em></strong></li></ul><p>The Builder pattern can be applied when construction of various representations of the product involves similar steps that differ only in the details.</p><h4>Implementation of Builder pattern :</h4><p>The most common use can be found in the <em>AlertDialog.Builder()</em> class :</p><pre>val builder = AlertDialog.Builder(this)<br>        builder.setTitle(&quot;Alert&quot;)<br>        builder.setMessage(&quot;Message&quot;)<br>   <br>   builder.setPositiveButton(android.R.string.yes){ dialog, which -&gt;<br>   }<br>         <br>   builder.setNegativeButton(android.R.string.no){ dialog, which -&gt;<br>   }</pre><pre>   builder.show()</pre><p>This builder proceeds step-by-step, and helps you specify just only the parts of your<em> AlertDialog </em>that you want.</p><p><strong><em>Another Example :</em></strong></p><p>In the below example, we have PersonalCar class with some properties such as type, model, and color. In this class, the type is significant and compulsory. Therefore, you have to pass it every time, but the rest of the properties are optional. Additionally, if you do not set any value, the default value will apply.</p><pre>   class PersonalCar(builder: Builder)<br>   {   <br>       private val type: String = builder.type<br>       private val model: String = builder.model<br>       private val color : String = builder.color</pre><pre>       class Builder(type: String)<br>       {    <br>          var type: String  =  type<br>          var model: String = &quot;Ford Figo&quot;<br>          var color: String = &quot;Black&quot;<br>         <br>          fun setType(type: String): Builder<br>          {      <br>             this.type = type<br>             return this   <br>          }</pre><pre>          fun setModel(model: String): Builder <br>          { <br>             this.model = model<br>             return this      <br>          }</pre><pre>          fun setColor(color: String): Builder<br>          {   <br>             this.color = color<br>             return this        <br>          }</pre><pre>          fun build(): PersonalCar<br>          {           <br>             return PersonalCar(this)<br>          }<br>       }<br>   }</pre><p>Now, we can use the Builder class as follows:</p><pre>PersonalCar.Builder(&quot;Ford&quot;) <br>    .setModel(&quot;Ford Freestyle&quot;)           <br>    .setColor(&quot;Red&quot;)    <br>    .build()</pre><p><em>Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21227ac392e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creational Design Patterns in Android: Singleton]]></title>
            <link>https://medium.com/@f.varmazyar992/android-design-patterns-the-singleton-pattern-377a85660160?source=rss-628b4df4962d------2</link>
            <guid isPermaLink="false">https://medium.com/p/377a85660160</guid>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Farnoosh Varmazyar]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 06:32:38 GMT</pubDate>
            <atom:updated>2021-08-21T10:46:34.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*u84JBbk1Pr0K_C0pwssjUA.jpeg" /></figure><p><strong>Introduction Singleton Design Pattern</strong></p><p>Singleton design pattern is categorized under creational design patterns. <br> The Singleton Pattern guarantees a class has one instance only and a global point of access to it is provided by that class. Anytime multiple classes or clients request for that class, they get the same instance of the class.</p><p>The Singleton pattern solves two problems at the same time:</p><p>1) <em>Ensure that a class has just a single instance.</em></p><p>Why would anyone want to control how many instances a class has? The most common reason for this is to control access to some shared resource for example, a database or a file.<br> Here’s how it works: imagine that you created an object, but after a while decided to create a new one. Instead of receiving a fresh object, you’ll get the one you already created.<br> Note that this behavior is impossible to implement with a regular constructor since a constructor call must always return a new object by design.</p><p><em>2) Provide a global access point to that instance.</em></p><p>Remember those global variables that you used to store some essential objects? While they’re very handy, they’re also very unsafe since any code can potentially overwrite the contents of those variables and crash the app.<br> Just like a global variable, the Singleton pattern lets you access some object from anywhere in the program. However, it also protects that instance from being overwritten by other code.<br> There’s another side to this problem: you don’t want the code that solves problem #1 to be scattered all over your program. It’s much better to have it within one class, especially if the rest of your code already depends on it.<br> Nowadays, the Singleton pattern has become so popular that people may call something a singleton even if it solves just one of the listed problems.</p><p><strong>Use case of Singleton design pattern</strong><br> But before moving into the example, you need to know that there are two common steps in every Singleton implementation.</p><ul><li>First step is to make the default constructor private, so it can prevent other objects from using the new operator with the Singleton class.</li><li>Then implement a static creation method that acts as a constructor.This method calls the private constructor to create an object and saves it in a static field. So, whenever this method gets called, it will return the object.</li></ul><p><strong>Note</strong>: The most common use case for applying Singleton design pattern is when dealing with databases.</p><h4>Example 01 : Classic Implementation</h4><p>It’s quite easy to implement this pattern. The following code snippet shows how a Singleton is created.</p><pre>public class Singleton  {</pre><pre>    private static Singleton INSTANCE = null;</pre><pre>//  other instance variables can be here</pre><pre>    private Singleton() {};</pre><pre>    public static Singleton getInstance() {<br>        if (INSTANCE == null) {<br>            INSTANCE = new Singleton();<br>        }<br>        return(INSTANCE);<br>    }<br>}</pre><p>In the code above, we have a static variable INSTANCE to hold an instance of the class. We also made the constructor private because we want to enforce noninstantiability — the class can only instantiate itself. The method getInstance() guarantees that the class is instantiated, if it has not been, and that it’s returned to the caller.</p><h4>Example 02 : Creating a Single Instance of Retrofit</h4><p>In an Android app, you’ll need a single global instance of a Retrofit object so that other parts of an app can use it to execute a network request without the need to create an instance every single time we need it.</p><pre>import retrofit2.Retrofit; <br>import retrofit2.converter.gson.GsonConverterFactory;</pre><pre>public class RetrofitClient {</pre><pre>    private static Retrofit retrofit = null;</pre><pre>    private RetrofitClient() {}</pre><pre>    public static Retrofit getClient(String baseUrl) {<br>        if (retrofit==null) { <br>            retrofit = new Retrofit.Builder()<br>              .baseUrl(baseUrl) <br>              .addConverterFactory(GsonConverterFactory.create())<br>              .build();<br>        } <br>        return retrofit;<br>    }<br>}</pre><p>So anytime client A calls RetrofitClient.getClient(), it creates the instance if it has not been created already, and then when client B calls this method, it checks if the Retrofit instance already exists. If so, it returns the instance to client B instead of creating a new one.</p><p><strong>Note :</strong> The main problem with above method is that it is not thread safe. <br> To solve the problem, it is better to implement the following method</p><pre>import retrofit2.Retrofit;<br>import retrofit2.converter.gson.GsonConverterFactory;</pre><pre>public class RetrofitClient {<br>    private static volatile Retrofit retrofit = null;<br>    private RetrofitClient() {}</pre><pre>    public static Retrofit getClient(String baseUrl) {<br>        if (retrofit==null) {<br>           synchronized (RetrofitClient.class) {<br>             retrofit = new Retrofit.Builder()<br>              .baseUrl(baseUrl)<br>              .addConverterFactory(GsonConverterFactory.create())<br>              .build();<br>           }<br>         }</pre><pre>        return retrofit;<br>    }<br>}</pre><p>We have declared the retrofit volatile which ensures that multiple threads offer the retrofit variable correctly when it is being initialized to RetrofitClient instance.</p><p><em>Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=377a85660160" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>