Abstract Factory mode:
In the previous article, through the various specific ball (such as: football, basketball, etc.) to inherit the ball, to achieve through the ballfactory to the specific ball production.
However, at that time only can create a different ball, and in each ball must also have color, size and other properties. So, in order to implement adding attributes in the factory. Add the abstract ball balls to the BLL interface and add the required methods to the interface:
This pattern is an abstract factory pattern, and abstract Factory mode is an upgrade of the abstract method pattern. When there are multiple business varieties, business grading, the use of abstract Factory mode production needs of the object is a very good solution room or. (for example, in the production of ball, not only the type of ball, but also the color of the ball, etc...)
That
1 // Ball Interface 2 Public Interface Ball {3 4 void Getballkind (); 5 6 void Getballcolor (); 7 }
And then let the ball be implemented by the specific balls of this interface
1 //Basketball realizes Ball2 Public Abstract classBasketballImplementsball{3 Public voidGetballkind () {4System.out.println ("I'm a basketball!!!");5 }6 }7 8 9 //Football realizes BallTen Public Abstract classFootball { One Public voidGetballkind () { ASystem.out.println ("I'm a football!!!"); - } -}
In this way, the type of ball can be produced in different ways. The next step is to paint the same ball in different colors.
1 //to paint a basketball2 Public classBlackbasketballextendsbasketball{3 4 Public voidGetballcolor () {5System.out.println ("I'm black basketball");6 }7 8 }9 Ten Public classRedbasketballextendsbasketball{ One A Public voidGetballcolor () { -System.out.println ("I am the Red basketball"); - } the - } - - //Coloring the Football + Public classBlackfootballextendsfootball{ - + Public voidGetballcolor () { ASystem.out.println ("I'm a black football!!!"); at } - } - - Public classRedfootballextendsfootball{ - - Public voidGetballcolor () { inSystem.out.println ("I am the Red football!!!"); - } to}
The balls of each breed are defined, and then they define the factories that produce each ball.
1 //Red Ball Factory class2 Public classRedballfactory implements ballfactory{3 4 PublicBall Createbasketball () {5 return NewRedbasketball ();6 }7 8 PublicBall Createfootball () {9 return NewRedfootball ();Ten } One } A //Black Ball Factory class - Public classBlackfactory implements ballfactory{ - the PublicBall Createbasketball () { - return NewBlackbasketball (); - } - + PublicBall Createfootball () { - return NewBlackfootball (); + } A}
The extensibility of the abstract factory pattern is general.
23 design mode----------Abstract Factory mode