Factory method Mode (Java and Kotlin version)

Source: Internet
Author: User

Forward push

Design Patterns

Simple Factory mode (Java and Kotlin Edition)

Kotlin Basic Knowledge

Kotlin first lesson: Starting with Java comparison

Kotlin Introductory Lesson II: Collection Operations

Kotlin Introductory Lesson Three: Data types

First attempt to implement Android projects with Kotlin

1. Definition

The factory method pattern (Factory mode), also known as the factory pattern, is called the virtual Constructor mode or the Polymorphic factory (polymorphic Factory) pattern, which belongs to the class-creation pattern. In factory method mode, the factory parent is responsible for defining the public interface that creates the product object, while the factory subclass is responsible for generating the specific product object, which is intended to defer the instantiation of the product class to the factory subclass, i.e., the factory subclass to determine which specific product class should be instantiated.

2. Structure

Factory: Abstract Factory role, defining an abstract method of creating an instance;

Concretefactory: Specific factory role, responsible for creating specific instances;

Product: The abstract production role, which is the parent of all objects created, is responsible for describing the common interfaces common to all instances;

Concreteproduct: The specific product role is to create the target, and all created objects act as instances of a specific class of this role.

3. Code

3.1 Java

Product:

1 abstract class Product {2     abstract void print (); 3} 

Defines the abstract product role, and the abstract method print.

Concreteproducta and CONCRETEPRODUCTB:

1 class Concreteproducta extends Product {2     void print () {3         System.out.println ("Print of Concreteproduc TA "    } 6  7 class CONCRETEPRODUCTB extends Product {8 void print () {9 System.out.println (" Print O F CONCRETEPRODUCTB " }11}      

Two specific product roles were defined, and the Print method was implemented separately.

Factory:

1 Abstract class Factory {2     Abstract Product FactoryMethod (); 3 }

Defines the abstract factory role, and the abstract method FactoryMethod.

Concretefactorya and Concretefactoryb:

1 classConcretefactorya extends Factory {2 Product FactoryMethod () {3System. out. println ("Create ProductA");4 5         return Newconcreteproducta ();6     }7 }8 9 classConcretefactoryb extends Factory {Ten Product FactoryMethod () { OneSystem. out. println ("Create PRODUCTB"); A  -         return NewCONCRETEPRODUCTB (); -     } the}

Two specific factory roles were defined, and the FactoryMethod method was implemented separately.

Factorymethodpattern:

1  Public classFactorymethodpattern {2      Public Static voidMain (string[] args) {3System. out. println ("Factory Method Pattern");4 5Factory Factory =NewConcretefactorya ();6Product Product =Factory.factorymethod ();7 product.print ();8 9Factory =NewConcretefactoryb ();TenProduct =Factory.factorymethod (); One product.print (); A     } -}

Different specific product instances, created with different specific factories.

Output:

3.2 Kotlin

Product:

1 abstract class Product {2     abstract fun print () 3} 

Concreteproducta and CONCRETEPRODUCTB:

1 class Concreteproducta:product () {2     override fun print () {3         println ("Print of Concreteproducta" c6/>} 6  7 class concreteproductb:product () {8 override fun print () {9 println ("Print of Concreteprodu CtB " }11}      

Factory:

1 Abstract class Factory {2     Abstract Fun FactoryMethod (): Product 3 }

Concretefactorya and Concretefactoryb:

1 classconcretefactorya:factory () {2     OverrideFun FactoryMethod (): Product {3println"Create ProductA")4 5         returnconcreteproducta ()6     }7 }8 9 classconcretefactoryb:factory () {Ten     OverrideFun FactoryMethod (): Product { Oneprintln"Create PRODUCTB") A  -         returnCONCRETEPRODUCTB () -     } the}

Factorymethodpattern:

1Fun Main (args:array<string>) {2println"Factory Method Pattern")3 4     varFactory:factory =Concretefactorya ()5     varProduct =Factory.factorymethod ()6 Product.print ()7 8Factory =Concretefactoryb ()9Product =Factory.factorymethod ()Ten Product.print () One}

Output ibid.

4. Pros and cons

4.1 Advantages

In the factory method model, the factory method is used to create the product that the customer needs, but also hides to the customer which specific product class will be instantiated this detail, the user only needs to care about the product corresponding factory, does not need to care about the creation detail, even does not need to know the specific product class the class name;

Polymorphism design based on plant roles and product roles is the key to the factory approach model. It enables the factory to determine which product objects are created autonomously, and the details of how to create the object are completely encapsulated inside a specific factory. The factory method pattern is also called the Polymorphic factory pattern because all the specific factory classes have the same abstract parent class;

Another advantage of using the factory method pattern is that when adding a new product to the system, it is not necessary to modify the interface provided by the abstract factory and the abstract product, without modifying the client, or modifying the other specific factories and specific products, as long as a specific factory and specific products can be added. In this way, the scalability of the system becomes very good, fully conform to the "open and close principle".

4.2 Disadvantages

When adding new products, it is necessary to write a specific product class, but also to provide the corresponding specific factory class, the number of classes in the system will increase in pairs, to a certain extent, increase the complexity of the system, there are more classes need to compile and run, the system will bring some additional overhead;

Due to the scalability of the system, it is necessary to introduce the abstraction layer, which is used in the client code to define the abstraction layer, which increases the abstraction and difficulty of comprehension, and it may need to use the techniques of DOM, reflection and so on to increase the difficulty of the system implementation.

5. Applicable scenarios

A class does not know the class of the object it needs: In the Factory method mode, the client does not need to know the class name of the specific product class, only need to know the corresponding factory, the specific product object is created by the specific factory class; The client needs to know the factory class that created the specific product;

A class specifies which object to create by its subclasses: in the factory method pattern, for the abstract factory class, you only need to provide an interface to create the product, and its subclasses determine the object to be created, take advantage of the object-oriented polymorphism and the Richter substitution principle, when the program runs, the subclass object will overwrite the parent class object. Thus making the system easier to expand;

Delegate the task of creating an object to one of several factory subclasses, which the client can use without having to care about which factory subclass creates a product subclass that is dynamically specified when needed, and stores the class name of the specific factory class in the configuration file or database.

Factory method Mode (Java and Kotlin version)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.