Factory model of Design Pattern

Source: Internet
Author: User

Factory model of Design Pattern
1. Concepts

Define an interface for creating an object, but let subclasses decide which class to instantiate. factory Method lets a class defer instantiation to subclasses. (define an interface used to create objects so that the subclass decides which class to instantiate. The factory method delays the instantiation of a class to its subclass .)
The factory model is one of the frequently used design patterns. The function is to initialize the delayed subclass. The client only needs to obtain the product from the factory, instead of understanding the product production details, thus reducing the coupling between modules. It is also an embodiment of interface-oriented programming.

2. generic class diagram

Picture taken from HeadFirst <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Release/aoaO + release + sa3vdO/2 qOsvt/M5bmks6fKtc/release + 38 zltcSy + release + jzfu/release + release/ydLUss6/release + release/vNfKwc + release = "3 "example> 3. Example

Example Background: There is a tablet factory that can produce Apple tablets and Android tablets. The tablet can be connected to wifi to disable wifi and other functions.

The example class diagram is as follows:

PAD interface code:

Package phlin. samples. factory. pad; public interface PAD {/*** networking function */public void linkToNet ();/*** enable wifi function */public void openWifi (); /***** disable the wifi function */public void closeWifi ();/***** other functions */}

Factory interface code:

Package phlin. samples. factory. pad;/*** flat panel factory interface * @ author lin **/public interface PADFactoryI {public PAD createPad (String padType );}

Android tablet code: [Implementing the tablet interface]

package phlin.samples.factory.pad;public class AndroidPad implements PAD {    @Override    public void linkToNet() {        // TODO Auto-generated method stub        UtilClass.Dis(I use a android pad to get msg from Intener);    }    @Override    public void openWifi() {        // TODO Auto-generated method stub        UtilClass.Dis(open android pad wifi);    }    @Override    public void closeWifi() {        // TODO Auto-generated method stub        UtilClass.Dis(close android pad wifi);    }}

Apple tablet code: [Implement tablet interface]

package phlin.samples.factory.pad;public class IOSPad implements PAD{    @Override    public void linkToNet() {        // TODO Auto-generated method stub        UtilClass.Dis(I use a IOS pad to get msg from Intener);    }    @Override    public void openWifi() {        // TODO Auto-generated method stub        UtilClass.Dis(open IOS pad wifi);    }    @Override    public void closeWifi() {        // TODO Auto-generated method stub        UtilClass.Dis(close IOS pad wifi);    }}

Factory implementation code: [implement factory interfaces]

package phlin.samples.factory.pad;public class PadFactory  implements PADFactoryI{    PAD pad=null;    @Override    public PAD createPad(String padType) {        // TODO Auto-generated method stub        if(padType.equals(android))        {            pad=new AndroidPad();        }else if(padType.equals(iso))        {            pad=new IOSPad();        }else        {            UtilClass.Dis(no instance);        }        return pad;    }      }

Secondary display class:

Package phlin. samples. factory. pad; public final class UtilClass {/*** terminal display * @ param str */public static void Dis (String str) {System. out. println (str );}}

Test code:

Package phlin. samples. factory. pad; public class TestClass {public static void main (String [] args) {PAD andPad = null, ios3= null; // The pad factory instantiates PadFactory factory = new PadFactory (); // produce Android tablet andPad = factory. createPad (android); andPad. linkToNet (); // produces an apple flat-panel ios3= factory. createPad (iso); ios3. linkToNet ();}}

Test results:

I use a android pad to get msg from IntenerI use a IOS pad to get msg from Intener

It can be found. In the test class code, only the factory needs to be instantiated, and then the corresponding flat can be instantiated through the createPad method. The key is that in the test class, how the flat is produced is not required, this greatly reduces the direct coupling of modules and facilitates expansion.

However, this String padType method makes it difficult to determine the type of products to be produced. If there are many styles, you must add them one by one. Here is a better optimization solution, which is implemented using generics and instantiated by class names directly.

The following changes are made to the factory interface and factory implementation class:
Note the differences:
Factory interface:

Package phlin. samples. factory. pad;/***** flat-panel factory interface * @ author lin **/public interface PADFactoryI {public
  
   
T ceratePad (Class
   
    
C );}
   
  

Factory implementation class:

package phlin.samples.factory.pad;public class PadFactory  implements PADFactoryI{    PAD pad=null;      @Override    public 
  
    T ceratePad(Class
   
     c) {        // TODO Auto-generated method stub        PAD pad=null;    try {        pad=(PAD)Class.forName(c.getName()).newInstance();    } catch (Exception e) {        // TODO: handle exception    }        return (T)pad;    }}
   
  

Test code:

package phlin.samples.factory.pad;public class TestClass {    public static void main(String[] args) {        PAD andPad=null,iosPad=null;        PadFactory factory=new PadFactory();        andPad=factory.ceratePad(AndroidPad.class);        andPad.linkToNet();        iosPad=factory.ceratePad(IOSPad.class);        iosPad.linkToNet();    }}

Test results:

I use a android pad to get msg from IntenerI use a IOS pad to get msg from Intener

The test results are the same, but for the factory implementation class, to add a new type of product, this class almost does not need to be changed. For products, you only need to expand the product, that is, the tablet type.

 

Related Article

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.