{"id":18,"date":"2012-07-20T14:23:15","date_gmt":"2012-07-20T13:23:15","guid":{"rendered":"http:\/\/oprsteny.cz\/?p=18"},"modified":"2012-07-20T14:38:02","modified_gmt":"2012-07-20T13:38:02","slug":"design-patterns-factory","status":"publish","type":"post","link":"https:\/\/oprsteny.cz\/?p=18","title":{"rendered":"Design Patterns &#8211; Factory"},"content":{"rendered":"<h1>Intent<\/h1>\n<ul>\n<li>Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to\u00a0subclasses.<\/li>\n<li>Defining a \u201cvirtual\u201d\u00a0constructor.<\/li>\n<li>The\u00a0<code>new<\/code>\u00a0operator considered\u00a0harmful.<!--more--><\/li>\n<\/ul>\n<h1>Problem<\/h1>\n<p>A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their\u00a0instantiation.<\/p>\n<h1>Discussion<\/h1>\n<p>Factory Method is to creating objects as Template Method is to implementing an algorithm. A superclass specifies all standard and generic behavior (using pure virtual \u201cplaceholders\u201d for creation steps), and then delegates the creation details to subclasses that are supplied by the\u00a0client.<\/p>\n<p>Factory Method makes a design more customizable and only a little more complicated. Other design patterns require new classes, whereas Factory Method only requires a new\u00a0operation.<\/p>\n<p>People often use Factory Method as the standard way to create objects; but it isn\u2019t necessary if: the class that\u2019s instantiated never changes, or instantiation takes place in an operation that subclasses can easily override (such as an initialization\u00a0operation).<\/p>\n<p>Factory Method is similar to Abstract Factory but without the emphasis on\u00a0families.<\/p>\n<p>Factory Methods are routinely specified by an architectural framework, and then implemented by the user of the\u00a0framework.<\/p>\n<h1>Structure<\/h1>\n<p>The implementation of Factory Method discussed in the Gang of Four (below) largely overlaps with that of Abstract Factory. For that reason, the presentation in this chapter focuses on the approach that has become popular\u00a0since.<\/p>\n<div><img decoding=\"async\" src=\"http:\/\/sourcemaking.com\/files\/sm\/images\/patterns\/Factory_Method.gif\" alt=\"Scheme of Factory Method\" \/><\/div>\n<p>An increasingly popular definition of factory method is: a\u00a0<code>static<\/code>\u00a0method of a class that returns an object of that class\u2019 type. But unlike a constructor, the actual object it returns might be an instance of a subclass. Unlike a constructor, an existing object might be reused, instead of a new object created. Unlike a constructor, factory methods can have different and more descriptive names (e.g.\u00a0<code>Color.make_RGB_color(float red, float green, float blue)<\/code>\u00a0and<code>Color.make_HSB_color(float hue, float saturation, float brightness)<\/code><\/p>\n<div><img decoding=\"async\" src=\"http:\/\/sourcemaking.com\/files\/sm\/images\/patterns\/Factory_Method_1.gif\" alt=\"Scheme of Factory Method\" \/><\/div>\n<p>The client is totally decoupled from the implementation details of derived classes. Polymorphic creation is now\u00a0possible.<\/p>\n<div><img decoding=\"async\" src=\"http:\/\/sourcemaking.com\/files\/sm\/images\/patterns\/Factory_Method__.gif\" alt=\"Scheme of Factory Method\" \/><\/div>\n<h1>Example<\/h1>\n<p>The Factory Method defines an interface for creating objects, but lets subclasses decide which classes to instantiate. Injection molding presses demonstrate this pattern. Manufacturers of plastic toys process plastic molding powder, and inject the plastic into molds of the desired shapes. The class of toy (car, action figure, etc.) is determined by the\u00a0mold.<\/p>\n<div><img decoding=\"async\" src=\"http:\/\/sourcemaking.com\/files\/sm\/images\/patterns\/Factory_Method_example1.gif\" alt=\"Example of Factory Method\" \/><\/div>\n<h1>Check\u00a0list<\/h1>\n<ol>\n<li>If you have an inheritance hierarchy that exercises polymorphism, consider adding a polymorphic creation capability by defining a\u00a0<code>static<\/code>\u00a0factory method in the base\u00a0class.<\/li>\n<li>Design the arguments to the factory method. What qualities or characteristics are necessary and sufficient to identify the correct derived class to\u00a0instantiate?<\/li>\n<li>Consider designing an internal \u201cobject pool\u201d that will allow objects to be reused instead of created from\u00a0scratch.<\/li>\n<li>Consider making all constructors\u00a0<code>private<\/code>\u00a0or\u00a0<code>protected<\/code>.<\/li>\n<\/ol>\n<h1>Rules of\u00a0thumb<\/h1>\n<ul>\n<li>Abstract Factory classes are often implemented with Factory Methods, but they can be implemented using\u00a0Prototype.<\/li>\n<li>Factory Methods are usually called within Template\u00a0Methods.<\/li>\n<li>Factory Method: creation through inheritance. Prototype: creation through\u00a0delegation.<\/li>\n<li>Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is\u00a0needed.<\/li>\n<li>Prototype doesn\u2019t require subclassing, but it does require an Initialize operation. Factory Method requires subclassing, but doesn\u2019t require\u00a0Initialize.<\/li>\n<li>The advantage of a Factory Method is that it can return the same instance multiple times, or can return a subclass rather than an object of that exact\u00a0type.<\/li>\n<li>Some Factory Method advocates recommend that as a matter of language design (or failing that, as a matter of style) absolutely all constructors should be private or protected. It\u2019s no one else\u2019s business whether a class manufactures a new object or recycles an old\u00a0one.<\/li>\n<li>The\u00a0<code>new<\/code>\u00a0operator considered harmful. There is a difference between requesting an object and creating one. The\u00a0<code>new<\/code>operator always creates an object, and fails to encapsulate object creation. A Factory Method enforces that encapsulation, and allows an object to be requested without inextricable coupling to the act of\u00a0creation.<\/li>\n<\/ul>\n<h1>Java example<\/h1>\n<pre lang=\"java\">public interface ImageReader {\r\n    public DecodedImage getDecodedImage();\r\n}\r\n\r\npublic class GifReader implements ImageReader {\r\n    public GifReader( InputStream in ) {\r\n        \/\/ check that it's a gif, throw exception if it's not, then if it is decode it.\r\n    }\r\n\r\n    public DecodedImage getDecodedImage() {\r\n       return decodedImage;\r\n    }\r\n}\r\n\r\npublic class JpegReader implements ImageReader {\r\n    \/\/...\r\n}<\/pre>\n<h1 lang=\"java\">C# example<\/h1>\n<pre lang=\"csharp\">using System;\r\nusing System.Collections;\r\n\r\n  class MainApp\r\n  {\r\n    static void Main()\r\n    {\r\n      \/\/ An array of creators \r\n      Creator[] creators = new Creator[2];\r\n      creators[0] = new ConcreteCreatorA();\r\n      creators[1] = new ConcreteCreatorB();\r\n\r\n      \/\/ Iterate over creators and create products \r\n      foreach(Creator creator in creators)\r\n      {\r\n        Product product = creator.FactoryMethod();\r\n        Console.WriteLine(\"Created {0}\", \r\n          product.GetType().Name);\r\n      }\r\n\r\n      \/\/ Wait for user \r\n      Console.Read();\r\n    }\r\n  }\r\n\r\n  \/\/ \"Product\" \r\n  abstract class Product\r\n  {\r\n  }\r\n\r\n  \/\/ \"ConcreteProductA\" \r\n  class ConcreteProductA : Product\r\n  {\r\n  }\r\n\r\n  \/\/ \"ConcreteProductB\" \r\n  class ConcreteProductB : Product\r\n  {\r\n  }\r\n\r\n  \/\/ \"Creator\" \r\n  abstract class Creator\r\n  {\r\n    public abstract Product FactoryMethod();\r\n  }\r\n\r\n  \/\/ \"ConcreteCreator\" \r\n  class ConcreteCreatorA : Creator\r\n  {\r\n    public override Product FactoryMethod()\r\n    {\r\n      return new ConcreteProductA();\r\n    }\r\n  }\r\n\r\n  \/\/ \"ConcreteCreator\" \r\n  class ConcreteCreatorB : Creator\r\n  {\r\n    public override Product FactoryMethod()\r\n    {\r\n      return new ConcreteProductB();\r\n    }\r\n  }<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Intent Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to\u00a0subclasses. Defining a \u201cvirtual\u201d\u00a0constructor. The\u00a0new\u00a0operator considered\u00a0harmful.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[6,4],"tags":[],"class_list":["post-18","post","type-post","status-publish","format-standard","hentry","category-creational-patterns","category-design-patterns"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p3nYbe-i","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/posts\/18","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=18"}],"version-history":[{"count":8,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/posts\/18\/revisions"}],"predecessor-version":[{"id":107,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=\/wp\/v2\/posts\/18\/revisions\/107"}],"wp:attachment":[{"href":"https:\/\/oprsteny.cz\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=18"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=18"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/oprsteny.cz\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=18"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}