Abstract Factory mode of "Java design mode"

Source: Internet
Author: User
Tags define abstract getcolor

1. The mistake of Nu wa

The previous section learned the factory model, Nu WA used the model successfully created three races, but the problem came, she found no gender ... It's a bit too big a mistake ... There is no sex, it is not ... Helpless, had to wipe off again, so everyone was wiped out, re-build people.

Nu WA began to analyze, since to distinguish between men and women, then the production of human plants (gossip stove) to be re-engineered, because a device is either all male, or all women. So the gossip stove can only be opened, the original one changed two, and slightly modified to become a female gossip stove and male gossip stove, so it can. So Nu WA began to prepare the production, she first drew a following:

Although this figure is a bit large, but not complex, she will humanfactory interface with two new interface inheritance, respectively with male and female characteristics, the original concrete human class also changed to abstract class, with two specific human class to inherit. Let's look at the implementation of NU WA:

First look at the human interface and several of its abstract classes:

Define abstract Human Interface public interface Human {public void GetColor ();p ublic void Talk ();p ublic void Getsex ();//More Sex}// Definition abstract yellow human public abstract class Abstractyellowhuman implements Human {@Override public void GetColor () {Syste    M.OUT.PRINTLN ("Yellow color");    } @Override public void Talk () {System.out.println ("Yellow people");  }}//abstract black and white people do not write, with the abstract yellow people the same//slightly//Yellow male class public class Maleyellowhuman extends Abstractyellowhuman {@Override public    void Getsex () {System.out.println ("Yellow man!"); A brief discussion on the}}//yellow women
The above omitted a similar code, the implementation of the same way, very simple, not verbose, so far, Nu wa to define the race, the following is to define the gossip stove:

Definition of the abstract Factory interface public interface Humanfactory {public Human Createyellowhuman ();p ublic Human Createblackhuman ();p ublic Human Createwhitehuman ();} Gossip stove for female production public class Femalefactory implements Humanfactory {     @Override     public Human Createyellowhuman () {        return New Femaleblackhuman ();    }      @Override     public Human createblackhuman () {        return new Femaleblackhuman ();    }     @Override     public Human Createwhitehuman () {        return New Femalewhitehuman ();    }}// Production men's gossip stove public class Malefactory implements Humanfactory {     @Override     public Human Createyellowhuman () {        return New Maleyellowhuman ();    }      @Override     public Human CreaTeblackhuman () {        return New Maleblackhuman ();    }     @Override     public Human createwhitehuman () {        return New Malewhitehuman ();    }}
Well, now the race has, gossip stove also has, Nu WA finally can make people again!

public class Nvwa {public static void main (string[] args) {humanfactory malehumanfactory = new Malefactory ();//First production line: Male Production line Humanfactory femalehumanfactory = new Femalefactory (); The second production line: female production line                //production line was completed, began to build human human Maleyellowhuman = Malehumanfactory.createyellowhuman ();//Yellow male human Femaleyellowhuman = Femalehumanfactory.createyellowhuman (); Making yellow female System.out.println ("-producing a yellow female-"); Femaleyellowhuman.getcolor (); Femaleyellowhuman.talk (); Femaleyellowhuman.getsex (); System.out.println ("--production of a yellow male--"); Maleyellowhuman.getcolor (); Maleyellowhuman.talk (); Maleyellowhuman.getsex () ;/* * ...... */}}
Here, the idea of the abstract factory model is sort of clear, and here's a look at the definition of the abstract factory pattern.

2. Definition of the abstract factory model

Abstract Factory pattern is a more commonly used pattern, defined as follows:

Provide an interface for creating families of related or dependent objects without specifying their concrete classes. is to provide an interface for creating a set of related or interdependent objects without specifying their specific classes. Its general class diagram is as follows:


Abstract Factory mode is an upgraded version of Factory mode, and it is a good solution to generate the required objects through the abstract Factory mode when there are multiple business varieties and business classifications. Let's take a look at the generic source code of the abstract factory European, first there are two mutually affected product lines (also called product families), such as the left and right door of the car, the two numbers should be equal-two objects between the constraints, each model of the door is different, this is the product level structure constraints, Let's take a look at the class diagram of two product families:


Note that the circle on the class diagram, the box corresponds to, two abstract product classes can have a relationship, such as the common inheritance or implementation of an abstract class or interface, the source code is as follows:

Public abstract class Abstractproducta {    //per product common method public    void Sharemethod () {        }    //per product the same method, different implementations    
The code for the two specific product implementation classes is as follows:

public class ProductA1 extends Abstractproducta {public    abstract void dosomething () {        System.out.println (" Product A1 Implementation Method ");    }} public class ProductA2 extends Abstractproducta {public    abstract void dosomething () {        System.out.println (" The method of realizing the product A2 ");    

Product B Similar to this, no longer repeat. Abstract Factory class Abstractcreator's responsibility is to define the functions that each factory implements, and in common code, the abstract factory class defines the product creation of two product families, as follows:

Public abstract class Abstractcreator {    //Create a product family public    abstract abstracproducta createproducta ();    Create B product Family public    abstract ABSTRACPRODUCTB CREATEPRODUCTB ();    
How do I create a product? This is done by a specific implementation class, and the Creator1 and Creator2 codes are as follows:

public class Creator1 extends Abstractcreator {    //produce only a product with product Grade 1 public    abstracproducta createproducta () {        return new ProductA1 ();    }    Only B products with product Grade 1 public    ABSTRACPRODUCTB CREATEPRODUCTB () {        return new ProductB1 ();    }} public class Creator2 Extends Abstractcreator {    //production of product Grade 1 for a product public    abstracproducta createproducta () {        return new ProductA2 ();    }    Only B products with product Grade 1 public    ABSTRACPRODUCTB CREATEPRODUCTB () {        return new ProductB2 ();    

Note: There are M product grades should have m to implement the factory class, in each implementation plant, to achieve different product family production tasks.

It is possible to produce an object unrelated to the implementation in a specific business, such as:

public class Abstractfactorytest {public    static void Main (string[] args) {        Abstractcreator creator1 = new Creator 1 ();        Abstractcreator Creator2 = new Creator2 ();        ABSTRACTPRODUCTA a1 = Creator1.createproducta ();        Abstractproducta A2 = Creator2.createproducta ();        ABSTRACTPRODUCTB B1 = CREATOR1.CREATEPRODUCTB ();        ABSTRACTPRODUCTB b2 = CREATOR2.CREATEPRODUCTB ();        ...    }

3. Advantages and disadvantages of the abstract factory model3.1 Advantages

1) encapsulation. Each product implementation class is not to be concerned about the high-level module, it is concerned about the interface, is abstract, it does not care how the object is created, which is responsible for the factory class, as long as the factory class is who, I can create a need for the object, save time and effort.

2) The constraints in the product family are non-public states. For example, the production of male and female proportions, speculation that Nu wa Niang must have their own plans, then in the abstract factory model, these constraints are implemented inside the factory.

3.2 Disadvantages

The biggest drawback of abstract Factory mode is that product family expansion is very difficult. If we want to add a product C, that is, the product family from the original A and B to 3, then we have to add the CREATEPRODUCTC () method in the abstract class Abstractcreator, and then the two implementation classes are modified ... Speaking of which, we already know the shortcomings of the expansion ...

Note that this is a difficult product family extension, not a product level extension. Product level expansion is also very easy to add a product level, as long as the addition of a factory class responsible for the newly added production tasks can be. That is to say, it is easy to scale and expand vertically.

Abstract Factory mode is introduced so much, if there are errors, welcome message ~

___________________________________________________________________________________________________________ __________________________________________

-----willing to share and progress together!

-----More articles please see: http://blog.csdn.net/eson_15

Abstract Factory mode of "Java design mode"

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.