{"componentChunkName":"component---src-templates-blog-post-js","path":"/factory-method-of-creational-patterns","result":{"data":{"contentfulBlogPost":{"createdAt":"2019-09-24T01:12:49.304Z","updatedAt":"2019-09-24T01:12:49.304Z","id":"9485c19d-e816-5a03-8707-b6493334b444","description":"It provides abstract methods to build instances and allow the sub-classes to change or override the methods to alter the instance that will be created.","title":"Factory Method of Creational Patterns","body":{"id":"1687a21c-0253-5045-ad89-ff2e61437083","childMarkdownRemark":{"id":"9d2a1814-d918-5777-8d73-fd80927be7f9","html":"<p>Sometimes when we have to create different instances and doing it with a basic form, could add complexity to the design. In those case, the creational patterns are used to control the creation process and hide the complexity at the same time.</p>\n<h2>Situation</h2>\n<p>Consider we are building an application to a <strong><em>Car Assembler Factory</em></strong>, which has to assemble the cars from different parts and they need to trade several models. For this example, the parts will be the <strong><em>Tires</em></strong> and the <strong><em>Engine</em></strong> but we need to take growth and diversity into account.</p>\n<h2>Description</h2>\n<p>In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.</p>\n<h3>UML Diagram</h3>\n<p><img src=\"https://www.dofactory.com/images/diagrams/net/factory.gif\" alt=\"src: https://www.dofactory.com/net/factory-method-design-pattern\"></p>\n<h3>Participants</h3>\n<p>The classes and interfaces participating in this pattern are:</p>\n<ul>\n<li><strong>Product</strong> as <em>IAutomobile</em>: defines the interface of objects the factory method creates.</li>\n<li><strong>ConcreteProduct</strong> as <em>Car and ElectricCar</em>: implements the Product interface.</li>\n<li><strong>Creator</strong> as <em>CarFactory</em>: declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.</li>\n<li><strong>ConcreteCreator</strong> as <em>ElectrictCar</em>: overrides the factory method to return an instance of a ConcreteProduct.</li>\n</ul>\n<h2>Implementation</h2>\n<p>Let's start creating the product interface, in this case the products would be our cars. We have to specify the common properties that might have every model we’ll assemble. At the end, they’re all automobiles:</p>\n<pre><code class=\"language-javascript\">interface IAutomobile {\n  tires: Tire[];\n  engine: Engine;\n}\n</code></pre>\n<p>Next, we build the class product (<strong>Car</strong>) extending the product interface, and each component (<strong>Tire and Engine</strong>) which belong to the product as classes.</p>\n<pre><code class=\"language-javascript\">class Car implements IAutomobile {\n    constructor(public tires: Tire[], public engine: Engine) { }\n}\n\nclass Tire {\n    constructor(public brand: string) { }\n}\n\nclass Engine {\n    constructor(public cylinder: number) { }\n}\n</code></pre>\n<blockquote>\n<p>These components are using a <strong>typescript</strong> feature for declaring properties with their level of access in the constructor.</p>\n</blockquote>\n<p>Now, we have to create the default implementation of the <em>CarFactory</em> class.</p>\n<pre><code class=\"language-javascript\">class CarFactory {\n  buildCar(): Car {}\n  joinTires(): Tire[] {}\n  createEngine(): Engine {}\n}\n</code></pre>\n<p>Let's start to dive into the methods which create the components need for the build of an average car.</p>\n<pre><code class=\"language-javascript\">joinTires(): Tire[] {\n    let tireSet = []\n\n    for (let i = 0; i &#x3C; 4; i++) {\n        tireSet.push(new Tire(\"Generic\"))\n    }\n\n    return tireSet\n}\n\ncreateEngine(): Engine {\n    return new Engine(4)\n}\n</code></pre>\n<blockquote>\n<p>The <strong><em>joinTires</em></strong> method iterate 4 times adding a generic tire object to an array and return it after. Meanwhile, <strong><em>createEngine</em></strong> return a simple instance of an Engine with 4 <em>cylinders</em>.</p>\n</blockquote>\n<p>After that, we put them into the <strong><em>buildCar</em></strong> method:</p>\n<pre><code class=\"language-javascript\">buildCar(): IAutomobile {\n\n    const tires = this.joinTires()\n    const engine = this.createEngine()\n\n    return new Car(tires, engine);\n}\n</code></pre>\n<p>Now, to build a car we just have to instantiate the <strong>CarFactory</strong> class and call its <strong><em>buildCar</em></strong> method:</p>\n<pre><code class=\"language-javascript\">const factory = new CarFactory()\n\nconst car = factory.buildCar()\n</code></pre>\n<p>The implementation of this pattern allows us create a new instance without the use of the <strong>new</strong> keyword operator. At first glance, this maybe seem useless but now we can override the method and change the returned class based on the product interface implemented.</p>\n<p>In case we have to create another model, like an electric car model, it must have obviously an electric engine.</p>\n<p>To achieve this, we just have to implement the <strong><em>IAutomobile</em></strong> interface to this new one product.</p>\n<pre><code class=\"language-javascript\">class ElectricCar implements IAutomobile {\n    constructor(public tires: Tire[], public engine: Engine) { }\n}\n</code></pre>\n<p>As we all know, the electric cars not use cylinders in their engine, so we should create a new class called <strong>ElectricEngine</strong>. This new class will be slightly different from its parent class Engine.</p>\n<pre><code class=\"language-javascript\">class ElectricEngine extends Engine {\n  constructor(batteryAh: number) {\n    super(0)\n  }\n}\n</code></pre>\n<p>Here, we change the constructor parameter with the <em>battery Ah</em> consume and using the <em>super</em> method to pass this value to the parent constructor.</p>\n<p>Next, we extend from the factory class to override the factory method and others we need (as <strong><em>createEngine</em></strong>).</p>\n<pre><code class=\"language-javascript\">class ElectricCarFactory extends CarFactory {\n  createEngine() {\n    return new ElectricEngine(3.8)\n  }\n\n  buildCar() {\n    const tires = this.joinTires()\n    const engine = this.createEngine()\n\n    return new ElectricCar(tires, engine)\n  }\n}\n</code></pre>\n<p>Mission accomplished, we can use another class with the same factory method to create a familiar product and keep the application design scalable.</p>\n<pre><code class=\"language-javascript\">const factory = new ElectricCarFactory()\n\nconst car = factory.buildCar()\n</code></pre>\n<blockquote>\n<p>You can check the full code example <a href=\"https://gist.github.com/ogaston/c0a7b539e1ff449bc4fe846041dc0b4b\">here</a></p>\n</blockquote>\n<h2>Consequence</h2>\n<p>In the preceding implementation, the factory method buildCar is who handle every step in the car assemble, but what about we have another model and it need an additional component? Fortunately, we have the same structure with the same outline, but that won't always happen.</p>\n<h2>When should be used?</h2>\n<p>There are a lot of situations of using it:</p>\n<ul>\n<li>when you don’t know beforehand the exact types and dependencies of the objects your code should work with.</li>\n<li>when you want to provide users of your library or framework with a way to extend its internal components.</li>\n</ul>\n<hr>\n<p>Comment bellow what is your ideal scenario to use the Factory Method pattern.</p>","excerpt":"Sometimes when we have to create different instances and doing it with a basic form, could add complexity to the design. In those case, the creational patterns are used to control the creation process and hide the complexity at the same time. Situation Consider we are building an…"}},"image":{"id":"8180f449-0414-51ff-9037-5ebbdfa9f32d","fluid":{"base64":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAMAAAAYGszCAAABj1BMVEX8uh38txL9xh/91Cr+2C79xR78uhX90Cf+1i38vRf8vBb+1Sv+5zv9xR3/6Tz/80X+6Dv90in9zyb9ySH8wBn9ySL/8kT/8UP9xyD8vhjh1Dr/70H+2i//6j39zSX7thJ2cSD57kSnegz1shL8uhRUPgf6thP96z9nYxz98kWlni3/6z5tTwjnqBD9xCb+3TJ3ahv9xh6HgSWupjDGvTb57UNvax7p3j/1sxJrTgjipBB0VQripxPi2D0/PBLPxjldWRuhmi3n3D/x5kF1cSHa0Dv88UQoJwvRmA9aQgixgQ3aohvSmQ9rTgnlphC/sjBFQxOpoi6Hgibx5kJZVhpJRhddWRyGgSV5dSHDuzX/9EUtKwysfQxuUAhZQw5OOQchGAR3VwleSgxKSBUzMQ5vax9xbSBhXhsAAAAdHAg+PBJ4dSGfmiwBAQBiRwhTPQe+ig4hGQQnJQsaGghFQxQiIQoDAwEGBgINDARsTwkvIgSFYgwWFQYMDAMEAwEPDw8tLS0oKCg9PT1BQUEcHBwTYHvxAAAACXBIWXMAABcRAAAXEQHKJvM/AAAAB3RJTUUH5gUfFCUldIuVigAAAKNJREFUGBllwc1KAmEYgNHnmXk/GSchLKFAaGM/u6CV0C108+4DV7ZIXWgYGYbTOE616ByRhlplX0ndEnTVTXSlpuIWGcie/JNG4SsgwqXvtHr7XDO4Iu+c0dosXlLKGHVuToqCxhDuKMu4V6ejD7j2+VbojVV8tDbhwT9P/lPFub+wFSWk8OCNqjp11dcAdjsYuKC2hjQnOFryYw7B0YUHMxrf14ogPRjXpOkAAAAASUVORK5CYII=","aspectRatio":1.425531914893617,"src":"//images.ctfassets.net/szbztvipepx3/1LpSxHcfWNIr2dNLGIk6Cg/debfbf5798452c63bd9c0749df92382a/descarga.png?w=786&q=50","srcSet":"//images.ctfassets.net/szbztvipepx3/1LpSxHcfWNIr2dNLGIk6Cg/debfbf5798452c63bd9c0749df92382a/descarga.png?w=197&h=138&q=50 197w,\n//images.ctfassets.net/szbztvipepx3/1LpSxHcfWNIr2dNLGIk6Cg/debfbf5798452c63bd9c0749df92382a/descarga.png?w=268&h=188&q=50 268w","srcWebp":"//images.ctfassets.net/szbztvipepx3/1LpSxHcfWNIr2dNLGIk6Cg/debfbf5798452c63bd9c0749df92382a/descarga.png?w=786&q=50&fm=webp","srcSetWebp":"//images.ctfassets.net/szbztvipepx3/1LpSxHcfWNIr2dNLGIk6Cg/debfbf5798452c63bd9c0749df92382a/descarga.png?w=197&h=138&q=50&fm=webp 197w,\n//images.ctfassets.net/szbztvipepx3/1LpSxHcfWNIr2dNLGIk6Cg/debfbf5798452c63bd9c0749df92382a/descarga.png?w=268&h=188&q=50&fm=webp 268w","sizes":"(max-width: 786px) 100vw, 786px"}}}},"pageContext":{"slug":"factory-method-of-creational-patterns","intl":{"language":"en","languages":["en","es"],"messages":{"title":"Omar Gaston","navbar.knowme":"About me","navbar.projects":"Projects","navbar.contact":"Contacts","frontpage.readMyBlog":"Read my blog","frontpage.knowme":"Who am I?","blog.subtitle":"Creating stories.","blog.title":"Sharing my ideas","blog.text":"with the community.","subscribe":"Subscribe","changeLanguage":"ES","goBack":"Go back","viewOnGithub":"View on Github","viewProject":"View Project","viewMore":"See more","notFound.title":"NOT FOUND","notFound.text":"You just hit a route that doesn't exist... what sadness! ","notFound.knowAuthor":"well, this guy","notFound.goBlog":"Better go and read something","notFound.whoSay":"...Who say that?","personal.title":"Who I Am?","personal.fullname":"Omar Gaston Chalas","personal.salute":"Hi, I'm","personal.presentation":"A Javascript Full-Stack Developer, Lover of creating products which make people's life easier.","personal.presentationContinue":"I'm always eager to hear about new ideas, create and learn new things.","personal.coverletter":"Well I'm Omar, a Dominican Software Engineer passionate about Javascript, web development and related technologies. As a developer, I've been building highly scalable business apps for more than 3+ years caring deeply about the details in both well-crafted code and user-facing experience. ","personal.coverletterContinue":"Since I remember, I've always been curious and eager to learn new technologies and acquire new skills. Constant learning and a proactivity attitude have allowed me to be comfortable with the rapid changes which are already common in the modern tech industry.","personal.coverletterContinue2":"Despite I care about keeping my technical skills shaped, I also have a Startup mindset and pragmatic attitude, that comes with a willingness to lead projects and desire to understand about the business and where it’s heading","personal.quote":"It's not all about me, As a team player, I love collaborating with others and be involved in Open Source projects. For me, mentoring and helping others is the best way to giving back to those whos have led me in the past.","personal.coverletterFooter":"By the way, These are some of the tools I'm currently using: ","aptitudes.title":"Skills","aptitudes.creativity.title":"Creativity","aptitudes.creativity.text":"The best way to demonstrate authenticity is by being creative.","aptitudes.innovation.title":"Innovation","aptitudes.innovation.text":"Experiment and apply new technologies.","aptitudes.focused.title":"Focus","aptitudes.focused.text":"The correct solutions arise by dividing a problem and focusing on each part.","aptitudes.consistency.title":"Consistency","aptitudes.consistency.text":"The only way to achieve success is to persevere.","aptitudes.simplest.title":"Simplicity","aptitudes.simplest.text":"It's always good when something works, but when it's simple and works, it's wonderful.","aptitudes.community.title":"♥","aptitudes.community.text":"Work as a team with communities and colleagues.","projects.title":"Projects","projects.text":"Some of the projects I've been working on","contact.title":"Contact","contact.text":"Talk to me and work together.","contact.form.email.label":"Email","contact.form.email.placeholder":"Your email","contact.form.message.label":"Message","contact.form.message.placeholder":"Anything about you, your work or your pet :)","contact.form.submit":"Send","contact.form.secondmessage":"Tell me, what's going on?","contact.writeme":"Write me!","lastPost.title":"Latest posts","search.result":"result","search.noresult":"No results for","search.search":"Search"},"routed":false,"originalPath":"/factory-method-of-creational-patterns","redirect":false}}}}