<?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 hitender pannu on Medium]]></title>
        <description><![CDATA[Stories by hitender pannu on Medium]]></description>
        <link>https://medium.com/@hitenpannu?source=rss-219bece0d489------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gpA4YPKVa3uNqNLxKIHypg.jpeg</url>
            <title>Stories by hitender pannu on Medium</title>
            <link>https://medium.com/@hitenpannu?source=rss-219bece0d489------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:27:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hitenpannu/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[Sliding Menu Demo Flutter]]></title>
            <link>https://hitenpannu.medium.com/sliding-menu-demo-flutter-e07977890558?source=rss-219bece0d489------2</link>
            <guid isPermaLink="false">https://medium.com/p/e07977890558</guid>
            <dc:creator><![CDATA[hitender pannu]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 08:10:02 GMT</pubDate>
            <atom:updated>2021-03-18T08:10:02.878Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Everyone, Flutter is the new buzz in the frontend world these days and If you have worked with it I am pretty sure you know how it improves the productivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*cm3lJbC8HmFq17XFOQEMfg.gif" /></figure><p>Below are the 5 things that we are going to use to create the sliding menu.</p><p><strong>Stateless Widget:</strong> As the name suggest its a widget without any state. This type of widgets is useful in case if that data we want to show in the widget is not going to change e.g Appbar etc.</p><p><strong>Stateful Widget: </strong>As the name suggest its a widget with a state. This type of widgets is useful in cases where the data that we want to show in the widget might change with user interaction, API requests etc. Whenever there is any change in state of the widget Flutter will redraw your widget.</p><p><strong>Animation Controller: </strong>This is the controller class for an animation. It allows us to play an animation in forward or reverse or stop that animation.<br>By default animation controller linearly produces values that range from 0.0 to 1.0, during a given duration. Animation Controller needs a Ticker Provider.</p><p><strong>Ticker Provider: </strong>Ticker provider is an interface that describes a factory for Ticker object. “Ticker” is an object that knows how to register itself with the “SchedulerBinding” and fires a callback every frame. Because of which any animation controller does not perform any calculation between two frames.</p><p><strong>Change Notifier:</strong> This is a class that is used for change notifications. Its kind of observers in java.</p><p>Let’s get started<br>Step1. Create A new Flutter project.<br>Step2. Go to projectName/lib/main.dart and delete everything.<br>Step3. Add below code to main.dart</p><pre><strong>import </strong>&#39;package:episodie_flutter/SlidingMenuDemo.dart&#39;;<br><strong>import </strong>&#39;package:flutter/material.dart&#39;;<br><br><strong>void </strong>main() =&gt; runApp(MyApp());<br><br><strong>class </strong>MyApp <strong>extends </strong>StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return new </strong>MaterialApp(<br>      title: &quot;Hidden Drawer&quot;,<br>      home: SlidingMenuDemo(),<br>    );<br>  }<br>}</pre><p>NOTE:<br>1. By passing MyApp Widget inside runApp() function, We are telling Flutter that MyApp Widget is the entry point of my application and root of the widget tree of my application.<br>2. Inside MyApp we are using MaterialApp which provides a material theme to complete app. It&#39;s not mandatory but its recommended.</p><p>Step4: Create Another dart class and name it SlidingMenuController</p><pre><strong>import </strong>&quot;package:flutter/material.dart&quot;;<br><br><strong>enum </strong>SlidingMenuState { closed, open, closing, opening }<br><br><strong>class </strong>SlidingMenuController <strong>extends </strong>ChangeNotifier {<br>  TickerProvider vsync;<br><br>  AnimationController _animationController;<br><br>  SlidingMenuState state = SlidingMenuState.closed;<br><br>  SlidingMenuController({<strong>this</strong>.vsync}) {<br>    _animationController = <strong>new </strong>AnimationController(<br>        vsync: vsync, duration: Duration(milliseconds: 250));<br><br>    _animationController.addListener(() {<br>      notifyListeners();<br>    });<br><br>    _animationController.addStatusListener((status) {<br>      <strong>switch </strong>(status) {<br>        <strong>case </strong>AnimationStatus.forward:<br>          {<br>            state = SlidingMenuState.opening;<br>            <strong>break</strong>;<br>          }<br>        <strong>case </strong>AnimationStatus.reverse:<br>          {<br>            state = SlidingMenuState.closing;<br>            <strong>break</strong>;<br>          }<br>        <strong>case </strong>AnimationStatus.completed:<br>          {<br>            state = SlidingMenuState.open;<br>            <strong>break</strong>;<br>          }<br>        <strong>case </strong>AnimationStatus.dismissed:<br>          {<br>            state = SlidingMenuState.closed;<br>            <strong>break</strong>;<br>          }<br>      }<br>      notifyListeners();<br>    });<br>  }<br><br>  <strong>get </strong>percentOpen {<br>    <strong>if </strong>(<strong>this</strong>._animationController == <strong>null</strong>) {<br>      <strong>return </strong>0.0;<br>    } <strong>else </strong>{<br>      <strong>return this</strong>._animationController.value;<br>    }<br>  }<br><br>  @override<br>  <strong>void </strong>dispose() {<br>    _animationController.dispose();<br>    <strong>super</strong>.dispose();<br>  }<br><br>  open() {<br>    _animationController.forward();<br>  }<br><br>  close() {<br>    _animationController.reverse();<br>  }<br><br>  toggle() {<br>    <strong>if </strong>(state == SlidingMenuState.open) {<br>      close();<br>    } <strong>else </strong>{<br>      open();<br>    }<br>  }<br>}</pre><p>This class controls the animation part and also notifies the listeners of this class about the change in the animation value.</p><p>Step5: Create SlidingMenu class</p><pre><strong>import </strong>&#39;package:episodie_flutter/SlidingMenuController.dart&#39;;<br><strong>import </strong>&#39;package:episodie_flutter/SlidingMenuDemo.dart&#39;;<br><strong>import </strong>&quot;package:flutter/material.dart&quot;;<br><br><strong>class </strong>SlidingMenu <strong>extends </strong>StatefulWidget {<br>  <strong>final </strong>Widget menuWidget;<br>  <strong>final </strong>Widget detailWidget;<br>  <strong>final </strong>MenuStatusChangeRequester menuStatusChangeRequester;<br><br>  SlidingMenu(<br>      {<strong>this</strong>.menuWidget, <strong>this</strong>.detailWidget, <strong>this</strong>.menuStatusChangeRequester});<br><br>  @override<br>  State&lt;StatefulWidget&gt; createState() {<br>    <strong>return </strong>_SlidingMenuState();<br>  }<br>}<br><br><strong>class </strong>_SlidingMenuState <strong>extends </strong>State&lt;SlidingMenu&gt;<br>    <strong>with </strong>TickerProviderStateMixin {<br>  <strong>static const </strong><em>_MAX_SLID_AMOUNT </em>= 278.0;<br><br>  SlidingMenuController menuController;<br><br>  @override<br>  <strong>void </strong>initState() {<br>    menuController = SlidingMenuController(vsync: <strong>this</strong>);<br>    menuController.addListener(() {<br>      setState(() {});<br>    });<br>    <strong>this</strong>.widget.menuStatusChangeRequester.addListener(() {<br>      menuController.toggle();<br>    });<br>    <strong>super</strong>.initState();<br>  }<br><br>  @override<br>  <strong>void </strong>dispose() {<br>    menuController.dispose();<br>    <strong>super</strong>.dispose();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return new </strong>Stack(<br>      children: &lt;Widget&gt;[<br>        <strong>this</strong>.widget.menuWidget,<br>        _transformWidget(<strong>this</strong>.widget.detailWidget)<br>      ],<br>    );<br>  }<br><br>  Widget _transformWidget(Widget target) {<br>    <strong>final </strong>slideAmount = <em>_MAX_SLID_AMOUNT </em>* menuController.percentOpen;<br>    <strong>final </strong>contentScale = 1.0 - (0.2 * menuController.percentOpen);<br>    <strong>final </strong>cornerRadius = 10 * menuController.percentOpen;<br>    <strong>final </strong>offset = 5.0 * menuController.percentOpen;<br>    <strong>final </strong>blurRadius = 20.0 * menuController.percentOpen;<br>    <strong>final </strong>spreadRadius = 10.0 * menuController.percentOpen;<br><br>    <strong>return new </strong>Transform(<br>      transform: <strong>new </strong>Matrix4.translationValues(slideAmount, 0.0, 0.0)<br>        ..scale(contentScale, contentScale),<br>      alignment: Alignment.<em>centerLeft</em>,<br>      child: <strong>new </strong>Container(<br>        child: ClipRRect(<br>          borderRadius: BorderRadius.circular(cornerRadius),<br>          child: target,<br>        ),<br>        decoration: BoxDecoration(boxShadow: [<br>          BoxShadow(<br>              color: Colors.<em>black87</em>,<br>              offset: Offset(0.0, offset),<br>              blurRadius: blurRadius,<br>              spreadRadius: spreadRadius)<br>        ]),<br>      ),<br>    );<br>  }<br>}</pre><p>NOTE:<br>1. This class is our main widget it basically takes two widgets which will be placed in a stack. <br>2. Detail Widget will be coming on the top and all the transformation will be done on the detail widget.</p><p>Step 6: Let’s Create our demo class</p><pre><strong>import </strong>&#39;package:episodie_flutter/SlidingMenu.dart&#39;;<br><strong>import </strong>&#39;package:flutter/material.dart&#39;;<br><br><strong>class </strong>SlidingMenuDemo <strong>extends </strong>StatelessWidget {<br>  MenuStatusChangeRequester menuStatusHandler = MenuStatusChangeRequester();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return new </strong>SlidingMenu(<br>      menuWidget: MenuWidget(<br>        menuStatusChangeRequester: menuStatusHandler,<br>      ),<br>      detailWidget: DetailWidget(<br>        menuStatusChangeRequester: menuStatusHandler,<br>      ),<br>      menuStatusChangeRequester: menuStatusHandler,<br>    );<br>  }<br>}<br><br><strong>class </strong>MenuWidget <strong>extends </strong>StatelessWidget {<br>  <strong>final </strong>MenuStatusChangeRequester menuStatusChangeRequester;<br><br>  MenuWidget({<strong>this</strong>.menuStatusChangeRequester});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return new </strong>Container(<br>      color: Colors.<em>red</em>,<br>    );<br>  }<br>}<br><br><strong>class </strong>DetailWidget <strong>extends </strong>StatelessWidget {<br>  <strong>final </strong>MenuStatusChangeRequester menuStatusChangeRequester;<br><br>  DetailWidget({<strong>this</strong>.menuStatusChangeRequester});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    <strong>return new </strong>Scaffold(<br>      appBar: <strong>new </strong>AppBar(<br>        title: Text(&quot;DEtails&quot;),<br>        leading: IconButton(<br>            icon: Icon(Icons.<em>menu</em>),<br>            onPressed: () {<br>              <strong>this</strong>.menuStatusChangeRequester.askSliderToToggle();<br>            }),<br>      ),<br>      body: <strong>new </strong>Container(<br>        color: Colors.<em>yellow</em>,<br>      ),<br>    );<br>  }<br>}<br><br><strong>class </strong>MenuStatusChangeRequester <strong>extends </strong>ChangeNotifier {<br>  askSliderToToggle() {<br>    notifyListeners();<br>  }<br><br>  slideBy(percent) {}<br>}</pre><p>NOTE: We have created another Change Notifier here that will be used by the menu and detail widget if they want to toggle the menu.</p><p><strong>COMPLETE PROCESS<br></strong>When a user clicks on the menu icon on the details screen. Detail screen calls the “askSliderToToggle” on “MenuStatusChangeRequester”. <br>The same instance of MenuStausChangeRequester is passed to SlidingMenu and SlidingMenu is added as a listener to MenuStatusChangeRequester.<br>So, calling “askSliderToToggle” on “MenuStatusChangeRequester” notifies “Sliding Menu”. <br>If you look into the SlidingMenu class</p><pre>@override<br><strong>void </strong>initState() {<br>  menuController = SlidingMenuController(vsync: <strong>this</strong>);<br>  menuController.addListener(() {<br>    setState(() {});<br>  });<br>  <strong>this</strong>.widget.menuStatusChangeRequester.addListener(() {<br>    menuController.toggle();<br>  });<br>  <strong>super</strong>.initState();<br>}</pre><p>We are asking our menu controller to perform toggle operation on receiving any notification from “MenuStatusChangeRequester”.</p><p>Let&#39;s take a look at what happens in our menu controller.</p><pre>open() {<br>  _animationController.forward();<br>}<br><br>close() {<br>  _animationController.reverse();<br>}<br><br>toggle() {<br>  <strong>if </strong>(state == SlidingMenuState.open) {<br>    close();<br>  } <strong>else </strong>{<br>    open();<br>  }<br>}</pre><p>We are starting the animation in case if the drawer is closed and reversing it incase drawer is open. Our SlidingMenuController is also extended from ChangeNotifier and we are notifying the listeners about the change in animation values using below line of code.</p><pre>_animationController.addListener(() {<br>  notifyListeners();<br>});</pre><p>If you look at the init method of _SlidingMenuState again. _SlidingMenuState is also added as listeners for the SlidingMenuController and every time it receives the notification it&#39;s calling its “setState” method.</p><p>Whenever “setState” is called flutter redraws the SlidingMenuWidget and if you look into “transformWidget” method. We are applying some transformations to the detail widget depending upon the current percentage of animation which gives us the sliding effect.</p><p>Thank you for your time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e07977890558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Factory And Abstract Factory in Android]]></title>
            <link>https://hitenpannu.medium.com/factory-and-abstract-factory-in-android-c93bd541b198?source=rss-219bece0d489------2</link>
            <guid isPermaLink="false">https://medium.com/p/c93bd541b198</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[android-design-patterns]]></category>
            <category><![CDATA[abstract-factory-pattern]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <dc:creator><![CDATA[hitender pannu]]></dc:creator>
            <pubDate>Sun, 20 Jan 2019 10:40:46 GMT</pubDate>
            <atom:updated>2019-01-20T16:44:11.967Z</atom:updated>
            <content:encoded><![CDATA[<p>Design Patterns have long been considered some of the most reliable and useful approaches for solving common software design problems.</p><p>Patterns provide general and reusable solutions to frequently occurring development issues, such as how to add functionality to an object without changing its structure or how to construct complex objects.</p><p>Most of the android developers started their development carrier with Android without having a complete understanding of the software architecture principles and design patterns. Though in the small applications these things work out but, as the application grows the bug count increases, the code base becomes messy.</p><p>To avoid these scenarios it is very important to understand the different patterns that are developed over the past years and are helping the developers in developing and maintaining large scale applications.</p><p>In this series, I will be discussing a number of patterns that can be used in Android applications.</p><p>Today I will be going through the <strong>Factory</strong> and <strong>Abstract Factory</strong> patterns. We will start from a very simple code base and iterate over the implementations to improve it and make use of these patterns.</p><h3>Let&#39;s get started</h3><p>For implementing the design patterns, we should understand the use case and the problem we are trying to solve. For our series, I will be building an app for a restaurant which delivers sandwiches you can think of it as the Subway.</p><p>Our app allows a user to create their own customized sandwich in which they can choose the kind of bread or the filling they wish to have.</p><p>Ok! Now, this sounds easy right, all we need to do is to create a different class for every bread type and every filling. We will give options to the user to select among those and we will be done right.</p><p><strong>So, let&#39;s do that -</strong></p><pre><strong>class </strong>Baguette {<br>    <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Baguette&quot;</strong>;<br>    }<br><br>    <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;65 kcal&quot;<br>    </strong>}<br>}<br><br><strong>class </strong>Brioche {<br>    <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Brioche&quot;<br>    </strong>}<br><br>    <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;85 kcal&quot;<br>    </strong>}<br>}<br><br><strong>class </strong>Cheese {<br>    <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Cheese&quot;<br>    </strong>}<br><br>    <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;105 kcal&quot;</strong>;<br>    }<br>}<br><br><strong>class </strong>Tomato {<br>    <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Tomato&quot;<br>    </strong>}<br><br>    <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;60 kcal&quot;<br>    </strong>}<br>}</pre><p>We have our classes for bread and fillings, now we are ready to use them and nothing will go wrong here if we are careful enough while using these classes.</p><p>Let’s use them</p><pre><strong>val </strong>bread = Brioche()<br><strong>val </strong>filling = Tomato()</pre><p>This looks good. We have created a new object Brioche and Tomato and assigned it to our bread and filling variables but there is a small problem as we know that Brioche is bread and Tomato is a filling but our code has no idea.</p><p><strong>So what to do now?</strong></p><p>Ok, We know how to fix this we need to create a “type” using interface and make our classes implement that interface.</p><p>Let&#39;s do that</p><pre><strong>interface </strong>Bread {}</pre><pre><strong>interface </strong>Filling {}</pre><p>And our class will become.</p><pre><strong>class </strong>Baguette : Bread{<br>    <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Baguette&quot;</strong>;<br>    }<br><br>    <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;65 kcal&quot;<br>    </strong>}<br>}<br><br><strong>class </strong>Brioche : Bread{<br>    <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Brioche&quot;<br>    </strong>}<br><br>    <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;85 kcal&quot;<br>    </strong>}<br>}<br><br><strong>class </strong>Cheese : Filling{<br>    <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Cheese&quot;<br>    </strong>}<br><br>    <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;105 kcal&quot;</strong>;<br>    }<br>}<br><br><strong>class </strong>Tomato : Filling{<br>    <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Tomato&quot;<br>    </strong>}<br><br>    <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;60 kcal&quot;<br>    </strong>}<br>}</pre><p>Cool, let&#39;s take another look at the code. We have common methods, and we can include them in our interfaces.</p><pre><strong>interface </strong>Bread {<br>    <strong>fun </strong>getName(): String;<br>    <strong>fun </strong>getCaloriesCount(): String;<br>}<br><br><strong>interface </strong>Filling {<br>    <strong>fun </strong>getName():String<br>    <strong>fun </strong>getCaloriesCount():String<br>}</pre><p>And our classes will become.</p><pre><strong>class </strong>Baguette : Bread{<br>    override <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Baguette&quot;</strong>;<br>    }<br><br>    override <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;65 kcal&quot;<br>    </strong>}<br>}<br><br><strong>class </strong>Brioche : Bread{<br>    override <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Brioche&quot;<br>    </strong>}<br><br>    override <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;85 kcal&quot;<br>    </strong>}<br>}<br><br><strong>class </strong>Roll : Bread {<br>    override <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Roll&quot;<br>    </strong>}<br><br>    override <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;75 kcal&quot;<br>    </strong>}<br>}<br><br><strong>class </strong>Cheese : Filling{<br>    override <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Cheese&quot;<br>    </strong>}<br><br>    override <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;105 kcal&quot;</strong>;<br>    }<br>}<br><br><strong>class </strong>Tomato : Filling{<br>    override <strong>fun </strong>getName(): String {<br>        <strong>return &quot;Tomato&quot;<br>    </strong>}<br><br>    override <strong>fun </strong>getCaloriesCount(): String {<br>        <strong>return &quot;60 kcal&quot;<br>    </strong>}<br>}</pre><p>This is perfect, now it will be easy to differentiate that bread and fillings.</p><p>But our usage code still looks the same. We still need to use the constructor of Brioche and Tomato. Wouldn’t it be nice if we can have someone to whom we can say “hey, I want this type of bread” and it will just create it and give it to us saving us from writing the constructor logic? <br>This is where the factory pattern comes into the picture. We just tell our factory that we want this type of object and it will create it and give it to us saving us from the constructor logic. <br>One thing to note here is that a factory should return only a single type of object.</p><pre><strong>class </strong>BreadFactory {<br>    <strong>fun </strong>getBread(breadType: String): Bread? {<br>        <strong>return when </strong>(breadType) {<br>            <strong>&quot;BRI&quot; </strong>-&gt; Brioche()<br>            <strong>&quot;BAG&quot; </strong>-&gt; Baguette()<br>            <strong>&quot;ROL&quot; </strong>-&gt; Roll()<br>            <strong>else </strong>-&gt; <strong>null<br>        </strong>}<br>    }<br>}</pre><pre><strong>class </strong>FillingFactory {<br>   <strong>fun </strong>getFilling(fillingType: String): Filling? {<br>        <strong>return when </strong>(fillingType) {<br>            <strong>&quot;CHE&quot; </strong>-&gt; Cheese()<br>            <strong>&quot;TOM&quot; </strong>-&gt; Tomato()<br>            <strong>else </strong>-&gt; <strong>null<br>        </strong>}<br>    }<br>}</pre><p>Now, we can make use them like</p><pre><strong>val </strong>breadFactory = BreadFactory().getBread(<strong>&quot;BRI&quot;</strong>)<br><strong>val </strong>fillingFactory = FillingFactory().getFilling(<strong>&quot;TOM&quot;</strong>)</pre><p>The additional benefit of this is that by looking at our factory we can know all the types of bread or types of fillings supported. This also makes it easy to add more types or breads and fillings.</p><p>What we did above is called <strong>factory pattern</strong> i.e creating a factory that will return us a particular type of object separating the <strong>construction logic</strong> from <strong>use.</strong></p><p>Everything looks good here and our app is also looking great and things are working perfectly as expected. Now with the growth of the business, We want to introduce more items in our app e.g drinks, cookies etc.</p><p>We can go ahead and create DrinkFactory and CookieFactory respectively and we should be able to use them without any issue.</p><p><strong>Let&#39;s have another look at our code base and see if we can improve it.</strong></p><p>When we look at any factory, we know all the implementations it can provide, wouldn’t be nice if we can have a factory which can provide us with different factories. In this way can make a single point of getting all the factories and our code base will be more organized.</p><p>We know that a factory returns the same type of object so let&#39;s create that type.</p><pre><strong>abstract class </strong>AbstractFactory {<br><br>    <strong>abstract fun </strong>getBread(breadType: String): Bread?<br><br>    <strong>abstract fun </strong>getFilling(fillingType: String): Filling?<br>}</pre><p>Now we will create a factory which will return other factory let’s call it FactoryGenerator.</p><pre><strong>class </strong>FactoryGenerator {<br><br>    <strong>companion object </strong>{<br>        <strong>fun </strong>getFactory(factory: String): AbstractFactory? {<br>            <strong>return when </strong>(factory) {<br>                <strong>&quot;BRE&quot; </strong>-&gt; BreadFactory();<br>                <strong>&quot;FIL&quot; </strong>-&gt; FillingFactory();<br>                <strong>else </strong>-&gt; <strong>null<br>            </strong>}<br>        }<br>    }<br>}</pre><p>We also need to make our factories extend the AbstractFactory.</p><pre><strong>class </strong>BreadFactory : AbstractFactory() {<br>    <strong>override fun </strong>getBread(breadType: String): Bread? {<br>        <strong>return when </strong>(breadType) {<br>            <strong>&quot;BRI&quot; </strong>-&gt; Brioche()<br>            <strong>&quot;BAG&quot; </strong>-&gt; Baguette()<br>            <strong>&quot;ROL&quot; </strong>-&gt; Roll()<br>            <strong>else </strong>-&gt; <strong>null<br>        </strong>}<br>    }<br><br>    <strong>override fun </strong>getFilling(fillingType: String): Filling? {<br>        <strong>return throw </strong>UnsupportedOperationException();<br>    }<br>}</pre><pre><strong>class </strong>FillingFactory : AbstractFactory() {<br>    <strong>override fun </strong>getBread(breadType: String): Bread? {<br>        <strong>return throw </strong>UnsupportedOperationException();<strong><br>    </strong>}<br><br>    <strong>override fun </strong>getFilling(fillingType: String): Filling? {<br>        <strong>return when </strong>(fillingType) {<br>            <strong>&quot;CHE&quot; </strong>-&gt; Cheese()<br>            <strong>&quot;TOM&quot; </strong>-&gt; Tomato()<br>            <strong>else </strong>-&gt; <strong>null<br>        </strong>}<br>    }<br>}</pre><p>We can use them like</p><pre><strong>val </strong>breadFactory = FactoryGenerator.getFactory(<strong>&quot;BRE&quot;</strong>)<br><strong>val </strong>bread = breadFactory?.getBread(<strong>&quot;ROL&quot;</strong>);<br><br><strong>val </strong>fillingFactory = FactoryGenerator.getFactory(<strong>&quot;FIL&quot;</strong>)<br><strong>val </strong>filling = fillingFactory?.getFilling(<strong>&quot;CHE&quot;</strong>)</pre><p>what we did now is called <strong>Abstract Factory Pattern </strong>i.e. A Factory that returns other factories.</p><p>BONUS:<br>If you like generics we can modify our abstract factory, a little and our code will change like this</p><pre><strong>abstract class </strong>AbstractFactory&lt;T&gt; {<br>    <strong>abstract fun </strong>getItem(type: String): T?<br>}</pre><pre><strong>class </strong>BreadFactory : AbstractFactory&lt;Bread&gt;() {<br>    <strong>override fun </strong>getItem(type: String): Bread? {<br>        <strong>return when </strong>(type) {<br>            <strong>&quot;BRI&quot; </strong>-&gt; Brioche()<br>            <strong>&quot;BAG&quot; </strong>-&gt; Baguette()<br>            <strong>&quot;ROL&quot; </strong>-&gt; Roll()<br>            <strong>else </strong>-&gt; <strong>null<br>        </strong>}<br>    }<br>}<br><strong>class </strong>FillingFactory : AbstractFactory&lt;Filling&gt;() {<br>    <strong>override fun </strong>getItem(type: String): Filling? {<br>        <strong>return when </strong>(type) {<br>            <strong>&quot;CHE&quot; </strong>-&gt; Cheese()<br>            <strong>&quot;TOM&quot; </strong>-&gt; Tomato()<br>            <strong>else </strong>-&gt; <strong>null<br>        </strong>}<br>    }<br>}<br><strong>class </strong>FactoryGenerator {<br><br>    <strong>companion object </strong>{<br>        <strong>fun </strong>getBreadFactory(): AbstractFactory&lt;Bread&gt; {<br>            <strong>return </strong>BreadFactory();<br>        }<br><br>        <strong>fun </strong>getFillingFactory(): AbstractFactory&lt;Filling&gt; {<br>            <strong>return </strong>FillingFactory();<br>        }<br>    }<br>}<br><strong>val </strong>breadFactory = FactoryGenerator.getBreadFactory()<br><strong>val </strong>bread = breadFactory.getItem(<strong>&quot;ROL&quot;</strong>);<br><br><strong>val </strong>fillingFactory = FactoryGenerator.getFillingFactory()<br><strong>val </strong>filling = fillingFactory.getItem(<strong>&quot;TOM&quot;</strong>)</pre><p>You can also create a live template for this. I have created one you can add it by going to Preferences-&gt; Editor-&gt; Live Templates-&gt; kotlin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFKkB2Ph08nq1eM8PBn0Ww.png" /></figure><p>and then we can use it like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*eDA1xKRzAA3XObKNFebbhw.png" /></figure><p>Thanks for spending your valuable time by reading this article. I hope it helps you out in one or another way-</p><p>Next, I will also be sharing more about other design patterns and how we can use them in our apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c93bd541b198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to G-Cloud command line tool]]></title>
            <link>https://medium.com/google-cloud/introduction-to-g-cloud-command-line-tool-f10834789b73?source=rss-219bece0d489------2</link>
            <guid isPermaLink="false">https://medium.com/p/f10834789b73</guid>
            <category><![CDATA[mutual-mobile]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[hitender-pannu]]></category>
            <dc:creator><![CDATA[hitender pannu]]></dc:creator>
            <pubDate>Wed, 17 Jan 2018 21:34:53 GMT</pubDate>
            <atom:updated>2018-01-19T00:10:21.920Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In this article I will give a brief introduction about “gcloud” command line tool which can be used to access the Google Cloud Resources.</blockquote><p>If this is the first time you are hearing about gcloud you should checkout this post “<a href="https://medium.com/@hitenpannu/creating-a-virtual-machine-in-google-cloud-platform-ec2d74dbbab0">Create simple virtual machine in Google Cloud Platform</a>” also you might wanna login to your google cloud account because I will start with the basics but then we will go deeper and explore it more so, If you want to see all the stuff in real time and remember it for lifetime you should run the commands that I will show you here.</p><p>In Google Cloud Platform you have the ability to access almost all the services in three ways:</p><ol><li>Google Cloud Console(Your dashboard)</li><li>GCloud(Command line tool available from google)</li><li>RestApi(You can also create apps to control your resources)</li></ol><p>Our focus for this article is gcloud Let’s get started</p><p><strong>What is gcloud ?</strong></p><blockquote>GCloud is a command line tool available from google that we can use to access google cloud services either using scripts or from command line and run other automations.</blockquote><p>Yes you can write scripts to spin up the instances according to your requirements, you can even set triggers to run those scripts but we will save those details for future.</p><p><strong>How can you access gcloud ?</strong></p><blockquote>GCloud is part of the Google Cloud SDK. You have to <a href="https://cloud.google.com/sdk/downloads">download and install the SDK</a> on your system and <a href="https://cloud.google.com/sdk/docs/initializing">initialize it</a> before you can use gcloud.</blockquote><p>GCloud will provide you access to for generally available commands by default. Now, you might be thinking that what are generally available commands. This is the release level of gcloud commands and yes there are more than one level.</p><p><strong>Levels of gcloud commands</strong></p><ol><li>General Availability</li><li>Beta</li><li>Alpha</li><li>Preview</li></ol><blockquote>Commands at General Availability level are considered as fully stable and production ready.</blockquote><blockquote>Commands at Beta level are fully functional but may still have some issues and thus they are not covered in any SLA(Service level Agreement)</blockquote><blockquote>Commands at Alpha level are in early release and may change without notice</blockquote><blockquote>Commands at Preview level may be unstable may change without notice</blockquote><p>Continuing on how to access the gcloud tool If you don’t want to install the SDK now you can use the Google Command Shell. It provides you with gcloud command-line access to computing resources hosted on Google Cloud Platform and available through the Google Cloud Platform Console. Cloud Shell is a Debian-based virtual machine with a persistent 5GB home directory, which makes it easy for you to manage your Cloud Platform projects and resources. With Cloud Shell, the Cloud SDK gcloudand other utilities you need are pre-installed and always available when you need them.</p><h3>Start Exploring</h3><p>First of all open your cloud console and start Google Command Shell by clicking on the top right icon in the toolbar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*noi-3QBGQwhsIQtx_NAX_Q.png" /></figure><p>Then click “Start Cloud Shell”. This will take few moments to provision and connect to the environment. When you start Cloud Shell, it provisions a <a href="https://cloud.google.com/compute/docs/machine-types">g1-small Google Compute Engine</a> virtual machine running a Debian-based Linux operating system. Cloud Shell instances are provisioned on a per-user, per-session basis. The instance persists while your Cloud Shell session is active and terminates after an hour of inactivity. I will be showing you more features of Google Cloud Shell in future but for now lets focus on gcloud .</p><p>After Cloud Shell is activated you can use the command line to invoke the Cloud SDK gcloud command or other tools available on the virtual machine instance.</p><h4>Getting started with commands</h4><p>Let’s start with my favorite command.</p><pre>gcloud -h</pre><p>Output of this will be</p><pre>Usage: gcloud [optional flags] &lt;group | command&gt;<br>  group may be           alpha | app | auth | beta | components | compute |<br>                         config | container | dataflow | dataproc | datastore |<br>                         debug | deployment-manager | dns | domains |<br>                         endpoints | firebase | iam | kms | logging | ml |<br>                         ml-engine | organizations | projects | pubsub |<br>                         service-management | services | source | spanner |<br>                         sql | topic<br>  command may be         docker | feedback | help | info | init | version<br><br>For detailed information on this command and its flags, run:<br>  gcloud --help</pre><p>You can clearly see from this that all the gcloud commands are divided into groups. Projects, Compute, Container all of these are different groups and each group contains commands relevant to that group. Alpha group is used to access alpha level commands and beta group is used to access beta level commands.</p><h4>Digging Deep</h4><p>We will be exploring compute group as we have prior understanding of instances from this <a href="https://medium.com/@hitenpannu/creating-a-virtual-machine-in-google-cloud-platform-ec2d74dbbab0">post</a>. You will find that running these commands is way cooler than controlling things from console as these commands are very straight forward and we can always look into help manual of command. Start by running</p><pre>gcloud compute -h</pre><p>Output will be something like</p><pre>Usage: gcloud compute [optional flags] &lt;group | command&gt;<br>  group may be           accelerator-types | addresses | backend-buckets |<br>                         backend-services | commitments | disk-types | disks |<br>                         firewall-rules | forwarding-rules | health-checks |<br>                         http-health-checks | https-health-checks | images |<br>                         instance-groups | instance-templates | instances |<br>                         interconnects | machine-types | networks | operations |<br>                         project-info | regions | routers | routes |<br>                         shared-vpc | snapshots | ssl-certificates |<br>                         target-http-proxies | target-https-proxies |<br>                         target-instances | target-pools | target-ssl-proxies |<br>                         target-tcp-proxies | target-vpn-gateways | url-maps |<br>                         vpn-tunnels | xpn | zones<br>  command may be         config-ssh | connect-to-serial-port | copy-files |<br>                         reset-windows-password | scp | ssh</pre><p>You can see that compute command is also divided into further groups. Lets compare these groups from the compute section on Google Cloud console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*4H4KUQZJTk9iUVksNqxAaQ.png" /></figure><p>You will notice that most of the groups available in the command output are same as they are available in console.</p><p>I will show you how easy is to create a virtual machine even if you don’t know any command using gcloud. I will use only the help command and will follow the documentation available in the help manual of that command.</p><p>I know the basic part that instances are part of compute right. So, I will run</p><pre>gcloud compute --help</pre><p>This will give me more verbose information about command and in that information I can see that there is a group named instances that can be used in reading and manipulating compute engine virtual machine instances.</p><pre>groups:</pre><pre>.......<br>instance-groups <br>        Read and manipulate Google Compute Engine instance groups.     <br>instance-templates<strong><br>        </strong>Read and manipulate Google Compute Engine   instances             templates.     <br><strong>instances<br>        Read and manipulate Google Compute Engine virtual machine instances.     </strong><br>interconnects<strong><br>        </strong>Read and manipulate Google Compute Engine interconnects.</pre><pre>........</pre><p>So, now I will move inside that group and run the help command again</p><pre>gcloud compute instances --help</pre><p>Now I will be seeing a bunch of commands that can be executed on this group like start, stop, attach-disk, delete, create etc. and I can also see the description of each command to avoid any confusion. So, I notice there is a command named “create”</p><pre>COMMANDS<br>.........</pre><pre>attach-disk <br>       Attach a disk to an instance. <br><strong>create</strong> <br><strong>       Create Google Compute Engine virtual machine instances. </strong>delete <br>       Delete Google Compute Engine virtual machine instances. delete-access-config <br>       Delete an access configuration from a virtual machine network interface.</pre><pre>..........</pre><p>So, I will now run</p><pre>gcloud compute instances create --help</pre><p>Output for above command will be something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*Bj1kEBJQdYoeTAJ30wquEw.png" /></figure><p>I can see the exact format that gcloud expects from me and all the possible parameters that I can pass to it. I can even look into the description provided below with information of all the available flags and there possible values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*gbQKmQsi0ogzivTs1r9xVQ.png" /></figure><p>So, I will run</p><pre>gcloud compute instances create my-instance --zone us-central1-c</pre><p>where my-instance is the name of my instance as specified in the description of the command and I will see something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dI8pJiNSGBzXCL3z_JSxtg.png" /></figure><p>I can also verify the instance creation from the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AQaErG-zuohfvYGwiObGw.png" /></figure><p>Now look at the command that we used carefully and see how clearly we are telling google cloud that I want to use its compute service for creating instance with name my-instance inside zone us-central1-c.</p><p>Believe me almost all the commands will be like this and you don’t have to learn any new language or you don’t have to remember anything all you have to do is use common sense and ask for help if required.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f10834789b73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/introduction-to-g-cloud-command-line-tool-f10834789b73">Introduction to G-Cloud command line tool</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Virtual Machine in Google Cloud Platform]]></title>
            <link>https://medium.com/google-cloud/creating-a-virtual-machine-in-google-cloud-platform-ec2d74dbbab0?source=rss-219bece0d489------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec2d74dbbab0</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[create-virtual-machine]]></category>
            <dc:creator><![CDATA[hitender pannu]]></dc:creator>
            <pubDate>Tue, 16 Jan 2018 19:55:24 GMT</pubDate>
            <atom:updated>2018-01-17T08:21:28.459Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will be showing you how to create a basic virtual machine in Google Cloud platform. We will start by basic overview of Google Cloud Platform after that I will show you how to create virtual machine instance of various machine types using Google cloud Platform. Let’s get started</p><p><strong>Google Cloud Platform overview</strong></p><p>Google Cloud platform is large set of physical assets such as computers, hard disk, processors and virtual assets such as Virtual Machines, services that are contained in Google Cloud data centers. Each data center is present in a global region and each region is a collection of zones. Each zone is isolated from each other within the same region. <br>This distribution provides us many facilities like data redundancy in case of zone failure, reduced latency by locating resources closer to client and also provided more control over resources and how they can be used to improve the service and reduce the cost.</p><p>As this is a cloud platform you don’t have to worry about physically buying the hardware, buying data centers and installing them. You can use all the hardware/software provided by google as services. In GCP these services provides you access to the underlying hardware. When you will start developing you will notice that you product is just a mix match of services provided by google and your code.</p><p><strong>Prerequisites</strong></p><p>Google account with billing enabled(If you are doing it for the first time just create a billing account using any credit/debit card with international transaction enables and you will get free credits from Google)</p><p><strong>Let’s Start</strong></p><p>First step will be to login to your Google cloud console and create a new project with any name you want. Now you might be thinking what is the role of project here I just want to create a virtual machine right?. So, think of project as an organizing entity. Any cloud platform resource that you allocate and use must belong to a project. After creating a project you will be able to see project info on your dashboard. This project info contains the project name which will help you to identify the project, Project ID which will help google cloud platform to identify your project and this will be unique for every project, Project Number which will be used by the support team incase you need any help with your project.</p><p>You have three ways to create a virtual machine</p><ol><li>Create using Google Cloud Console.</li><li>Create using “gcloud” command line tool.</li><li>Create using Compute Engine REST API</li></ol><p>In this article I will show you it using Google Cloud console and gcloud</p><p><strong>Creating Virtual Machine Using Google Cloud Console</strong></p><p>Click menu icon on the top left of the screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*et6Sz7mkBTcMRzbfCQW2ag.png" /></figure><p>Then navigate to Compute engine and VM instances. It may take some time for the first time when you click on VM instances but once its initialized you will see something like this(keep in mind you need to enable billing for your project to see this).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivms3f2klEoFAD42x3MyQQ.png" /></figure><p>Click on create then you will see this page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h08sOPM6pcHEKuYcOwT8Nw.png" /></figure><p>As you can see here you can specify the name of the instance that you want to create. Specify the zone in which you want to create this instance. You can select the machine type that you want to use for your instance. There are large number of machines available from which you can select depending upon your requirement. You can even customize and create your own machine type.</p><p>You can also choose the boot disk that you want to use to boot this virtual machine from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*eaA9pWft4CIB6bl0X6WGCg.png" /></figure><p>You can select the service account which will be used by this instance. Don’t worry about service account right now just think of it as a way for Google Cloud Platform to identify and authorize your virtual machine in case if it wants to communicate with other services of GCP.</p><p>Now, to allow incoming and outgoing traffic we have firewall rules and those are applied to Virtual Machines using tags.</p><p>There are customizations available related to management, disks, SSH etc. We will look into them in future. For now just click on create.</p><p>This creation process is asynchronous but once the instance is created you will see a green checkmark with the name of the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_ZGMiCnJjthUNlDKeCzjQ.png" /></figure><p>Congratulations you have successfully created a virtual machine. Hmm..<br>you might be thinking its very boring as you haven’t use what you have created. So, I will give you a little trailer of what you can do from here.</p><p>Click on the SSH link that you are seeing there. You will be able to see the console of your virtual instance and the cool thing is you have the root access for it without doing anything. So, without wasting any time just login as root user by running</p><pre>sudo su -</pre><p>this will give login you as root and you will see something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*ZZc6A41g0R5qlis9hCXj4w.png" /></figure><p>where “instance-1” is the name of your instance. Now the first and most important thing update your OS by running</p><pre>apt-get update</pre><p>This will update your instance with all the security patches and many other things and finally install the nginx server</p><pre>apt-get install nginx -y</pre><p>once installation is done check if nginx is running using</p><pre>ps auwx | grep nginx</pre><p>Awesome! Now go to your console and click on the external IP. You should see the default page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*koQnuDxNv-VYfJXSCp51dA.png" /></figure><p>So, who thought having your own server will be that easy right?.</p><p>You can do all these things with “gcloud” also. Generally “gcloud” will be used in case when you want to create instances using scripts. But for now let’s see how can we create a simple instance with all the default values.</p><p><strong>Creating Virtual Machine Using gcloud</strong></p><p>gcloud is a command line tool available from google we can install it in our systems or we can use Google command shell which have many packages preinstalled and provides a memory of about 5GB. For our purpose we will be using Google command shell. You can open cloud shell by clicking on the icon on the top right of the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*tkX6XGORxVArBA9nUmG3ug.png" /></figure><p>Once opened you can create a virtual machine instance using command</p><pre>gcloud compute instances create instance-1 --zone us-central1-c</pre><p>Virtual Machine is a zonal resource so we must specify the zone in which we want to create our instance and also we cannot have instances with same name in same zone under same project. You can also explore more options under compute using</p><pre>gcloud compute instances create — help</pre><p>It will ask you create passphrase for your vm instance. Just click enter if you want to create an empty passphrase.</p><p>In future we will be exploring more options to customize our virtual machines and how to modify the firewall rules, improve security for vm instances, grouping them etc. We will also explore the “gcloud” command line tool.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec2d74dbbab0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/creating-a-virtual-machine-in-google-cloud-platform-ec2d74dbbab0">Creating a Virtual Machine in Google Cloud Platform</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>