Android Design mode-factory method mode

Source: Internet
Author: User
Tags export class concurrentmodificationexception

1. Definition:

Define an interface for creating a object, but let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to subclasses.

Defines an interface that is used to create an object so that the subclass decides which class to instantiate.


2, meaning:

The factory method extends the instantiation of the class to the subclass.


3. Four major roles:

3.1. Abstract Factory: The core of the factory method pattern, any factory class that creates objects in the schema must implement this interface.

3.2, Specific factory: the implementation of the abstract factory interface specific Java class. The specific factory role contains logic that is closely related to the business and is invoked by the consumer to create an export class.

3.3. Abstract role: The superclass of the object created by the factory method pattern.

3.4. Specific role: an instance of a specific role that implements an abstract role.


4. Advantages:

4.1, the factory method mode is fully in line with the open and closed principle;
4.2, rejected the simple factory model shortcomings;
4.3, the Factory mode is a typical decoupling mode, can reduce the coupling degree between the objects;
4.4, the factory model relies on the abstract architecture, it is the task of the instantiation of the product to the implementation of the class completion, the scalability is better.

4.5, can make the code structure clear, effectively package changes.

4.6. Block specific product classes for callers. If you use Factory mode, the caller only cares about the interface of the product, and as for the specific implementation, the caller doesn't have to care. Even if a specific implementation is changed, it has no effect on the caller.


5. Disadvantages:

When a simple object is applied, the factory method pattern is not appropriate.


6, wrote a simple demo:

The first is the ordinary abstract object

<span style= "FONT-SIZE:14PX;" >package com.example.demo.factorymethod;/** * Abstract </span><span style= "FONT-SIZE:12PX;" ><span style= "font-family:arial;" > Role </span></span><span style= "FONT-SIZE:14PX;" > * @author Qubian * @data June 4, 2015 * @email [EMAIL protected] * */public interface Lottery {public String Getlotteryn Ame ();} </span>
implementation:

Package com.example.demo.factorymethod;/** * Specific characters * @author Qubian * @data June 4, 2015 * @email [EMAIL protected] * */public Class Ssqlottery implements lottery{@Overridepublic String Getlotteryname () {return ' Color Ball ';}}  Package com.example.demo.factorymethod;/** * Specific characters * @author Qubian * @data June 4, 2015 * @email [EMAIL protected] * */public Class Dltlottery implements lottery{@Overridepublic String Getlotteryname () {return "Lotto";}}

Then is the core of the abstract factory:

Package com.example.demo.factorymethod;/** * Abstract Factory * @author Qubian * @data June 4, 2015 * @email [EMAIL protected] * */public Interface Lotteryfactory {public lottery getlottery ();}

Specific factory:

Package com.example.demo.factorymethod;/** * Specific Factory * @author Qubian * @data June 4, 2015 * @email [EMAIL protected] * */public Class Ssqfactory implements lotteryfactory{@Overridepublic lottery Getlottery () {return new Ssqlottery ();}}  Package com.example.demo.factorymethod;/** * Specific characters * @author Qubian * @data June 4, 2015 * @email [EMAIL protected] * */public Class Dltlottery implements lottery{@Overridepublic String Getlotteryname () {return "Lotto";}}

Use:

Package Com.example.demo.factorymethod;import android.util.log;/** * Factory Method Use *  * @author Qubian * @data June 4, 2015 * @e mail [email protected] * */public class Usefactory {private static final String tag= "usefactory";p ublic Void Use () {//If need to be repaired Change, you only need to modify the new Ssqfactory (); //lotteryfactory factory= new Ssqfactory ();//Operation done here is the operation of the interface;//That is to say: Using the Factory mode, the caller only cares about the interface of the product can be,//as to the specific implementation, the caller does not need to care. Even if a specific implementation is changed, it has no effect on the caller. Lottery lottery = Factory.getlottery (); LOG.I (Tag,lottery.getlotteryname ());}}

The use of Android in a wide range of which:

1, about ArrayList, HashSet, with Iterator can be regarded as a kind of factory method;

set<string> set = new hashset<string> ();iterator<string> Iterator = Set.iterator (); while ( Iterator.hasnext ()) {//specific operation}list<string> List =new arraylist<string> ();iterator<string> it = List.iterator (); while (It.hasnext ()) {//Specific action}

Where list and set are factory interfaces
/** * A {@code Set} is a data structure which does not allow duplicate elements. * * @since 1.2 */public interface set<e> extends collection<e>{/** * Returns an iterator on the Elemen TS of this {@code List}.     The elements is * iterated in the same order as they occur in the {@code List}.     * * @return An iterator in the elements of this {@code List}. * @see Iterator */public iterator<e> Iterator ();} /** * A {@code List} is a collection which maintains an ordering for its elements. Every * element in the {@code List} have an index. Each element can thus is accessed by it * index, with the first index being zero. Normally, {@code list}s allow duplicate * elements, as compared to sets, where elements has to be unique. */public interface List<e> extends collection<e> {/** * Returns an iterator on the elements of this {@ Code List}.     The elements is * iterated in the same order as they occur in the {@code List}.   *  * @return An iterator in the elements of this {@code List}. * @see Iterator */public iterator<e> Iterator ();}


Naturally, ArrayList and hashmap all have a realization about it.

public class Arraylist<e> extends abstractlist<e> implements Cloneable, Serializable, randomaccess {@Overr    IDE public iterator<e> Iterator () {return new arraylistiterator (); } Private class Arraylistiterator implements Iterator<e> {/** number of elements remaining in this Iterat        ION */Private int remaining = size;        /** Index of element that remove () would remove, or-1 if no such ELT */private int removalindex =-1;        /** the expected Modcount value */private int expectedmodcount = Modcount;        public Boolean Hasnext () {return remaining! = 0;            } @SuppressWarnings ("Unchecked") public E Next () {arraylist<e> ourlist = arraylist.this;            int rem = remaining;            if (ourlist.modcount! = Expectedmodcount) {throw new concurrentmodificationexception (); } if (rem = = 0) {throw new nosuchelementexceptIon ();            } remaining = Rem-1;        Return (E) Ourlist.array[removalindex = Ourlist.size-rem];            } public void Remove () {object[] a = array;            int removalidx = Removalindex;            if (modcount! = Expectedmodcount) {throw new concurrentmodificationexception ();            } if (Removalidx < 0) {throw new illegalstateexception ();            } system.arraycopy (A, Removalidx + 1, A, removalidx, remaining);  A[--size] = null;            Prevent memory Leak removalindex =-1;        Expectedmodcount = ++modcount; }    }}



Android Design mode-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.