Factory method Mode

Source: Internet
Author: User
Tags abstract definition

Factory Method Mode

    • Factory Method Mode : Defines an interface for creating an object, letting subclasses decide which class to instantiate. The factory method defers the instantiation of a class to its subclasses. (Define an interface for creating a object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses).
    • In the factory method model, the abstract product class product is responsible for defining the commonality of the product, realizing the most abstract definition of the thing, creator creating the class for abstraction, which is the abstract factory, and how to create the product class is done by the concrete implementation factory Concretecreator. The class diagram is as follows:

 Public Abstract classProduct {//abstract methods for product classes     Public Abstract voidMethod1 (); //public methods for product classes     Public voidMethod2 () {System.out.println ("Abstract Product"); }} Public classConcreteProduct1extendsproduct{@Override Public voidMethod1 () {//TODO auto-generated Method Stub            }} Public Abstract classCreator { Public Abstract<textendsProduct> T createproduct (class<t>c);} Public classConcretecreatorextendscreator{@Override Public<textendsProduct> T createproduct (class<t>c) {//TODO auto-generated Method StubProduct Product =NULL; Try{Product=(Product) Class.forName (C.getname ()). Newinstance (); } Catch(instantiationexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        return(T) product; }} Public classclient{ Public Static voidMain (string[] args) {Creator Creator=NewConcretecreator (); Product Product= Creator.createproduct (ConcreteProduct1.class); Product.        Method1 (); Product.    METHOD2 (); }}
    • Advantages of factory method mode :
      • Good encapsulation, code structure is clear, an object is created with conditional constraints, such as a caller needs a specific product object, As long as you know the class name of the product (constraint string), reduce the coupling between the modules
      • easy to expand, in the case of adding product classes, As long as you modify the specific factory class appropriately or extend a factory class, you can do so.
      • shielding the product class, how the product class changes, the caller does not care, it only needs to care about the interface of the product, as long as the interface remains unchanged, The upper module of the system will not change
      • factory method mode is a typical decoupling framework. High-level modules only need to know the product of the abstract class, other implementation classes do not care, in line with the Dimitri Law, do not need to communicate, also comply with the principle of dependency inversion, but also in line with the Richter replacement principle.
    • factory method Use scene

First, the factory method pattern can be used where objects need to be created, but it is prudent to consider whether to add a factory class to manage and increase the complexity of the code. Second, when you need a flexible, extensible framework, consider using a factory method pattern. For example, the design of a connection to the mail server framework, there are three kinds of network protocols to choose from: POP3, IMAP, HTTP, we can use these three connection methods as product classes, define an interface such as Iconnectmail, and then define the method of operation of the message, In different ways to achieve three specific product classes (connection), and then define a factory method, according to different incoming conditions, choose a different connection mode. This design allows for perfect expansion, such as the WebService interface provided by some mail servers, and only one product class can be added.

    • Factory method mode and Singleton mode

Factory method mode and singleton mode are all part of creating class mode, then we can use factory method mode instead of Singleton mode.

      • The core requirement of the singleton pattern is that there is only one object in memory, and a factory method pattern can also produce an object in memory. The class diagram is as follows:

 Public classSingleton {PrivateSingleton () {} Public voiddosomething () {}} Public classSingletonfactory {Private Static classsingletonholder{Private StaticSingleton Singleton; Static{            Try{Class<?> cl = Class.forName (Singleton.class. GetName ()); Constructor<?> constructor =Cl.getdeclaredconstructor (); Constructor.setaccessible (true); Singleton=(Singleton) constructor.newinstance (); }Catch(Exception e) {e.printstacktrace (); }        }    }     Public StaticSingleton Getsingleton () {returnSingletonholder.singleton; }}

Singletonfactory cannot create objects by new means, you might ask how the factory method pattern creates objects? The answer is created in a reflective fashion. "A hungry man" cannot be used to create an object, it is initialized with a static inner class, and the advantage of a static inner class is that it is not necessary to instantiate the singleton object when the current class is loaded, but rather to instantiate the object when the Getsingleton () method is called.

    • Deferred initialization (lazy initialization)

Once an object is consumed, it is not immediately released, and the factory class remains in its initial state, waiting to be used again. Lazy initialization is an extended application of the factory method pattern, and its general class diagram is as follows:

 Public classProductfactory {Private Static Finalhashmap<string, product> prmap =NewHashmap<string, product>();  Public Static synchronizedProduct createproduct (String type) {Product Product=NULL; if(Prmap.containskey (type)) product=prmap.get (type); Else{            Try{Product=(Product) class.forname (type). Getdeclaredconstructor (). newinstance ();            Prmap.put (type, product); }Catch(Exception e) {e.printstacktrace (); }        }        returnproduct; }}

The code is simple, by defining a hashmap container to hold all the product objects, when you need to create an object, first find the current key from Prmap, then return directly, otherwise create the current object and add the created object to the Prmap for the next call. This method can also limit the maximum number of instantiations of a class of products, such as the JDBC Connection database, which sets a maximum number of maxconnection connections, which is the maximum number of instances in memory.

    • Best practices

The factory method pattern can be mixed with other modes (template method mode, singleton model, prototype model, etc.), which can change the infinite excellent design, hoping that the reader will realize it in practice.

Factory method Mode

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.