Time is pressing, there is a lot of content about the factory model, the words are roughly divided into simple factory model, factory method model, abstract factory model
Here, I would like to talk about the simple factory model, but also in our actual development with relatively more
The first step is to create a factory interface that specifies what the factory is for:
1 /*2 * Created by: Ouyangshengduo3 * Date of creation: March 31, 20174 * File name: Hairinterface.java5 * Copyright information: Edan. All rights reserved. 6 * File Description: Hairstyle interface7 */8 Packagecom.oysd.model.factory;9 Ten Public InterfaceHairinterface { One A //achieve a hairstyle - Public voidDraw (); - the}
The second step, the realization of different product specific content
1 /*2 * Created by: Ouyangshengduo3 * Date of creation: March 31, 20174 * File name: Lefthair.java5 * Copyright information: Edan. All rights reserved. 6 * File Description:7 */8 Packagecom.oysd.model.factory;9 Ten Public classLefthairImplementsHairinterface { One A /** - * Draw a left-biased distribution - */ the @Override - Public voidDraw () { - //TODO auto-generated Method Stub - +System.out.println ("-----------implements a left-biased distribution-----------"); - } + A}
1 /*2 * Created by: Ouyangshengduo3 * Date of creation: March 31, 20174 * File name: Righthair.java5 * Copyright information: Edan. All rights reserved. 6 * File Description:7 */8 Packagecom.oysd.model.factory;9 Ten Public classRighthairImplementsHairinterface { One A - /** - * Draw a right-biased hairstyle the */ - @Override - Public voidDraw () { - //TODO auto-generated Method Stub +System.out.println ("-----------implements a right-biased distribution-----------"); - } + A}
Create a factory class
1 /*2 * Created by: Ouyangshengduo3 * Date of creation: March 31, 20174 * File name: Hairfactory.java5 * Copyright information: Edan. All rights reserved. 6 * File Description:7 */8 Packagecom.oysd.model.factory;9 Ten Public classHairfactory { One A /** - * Create factory for hairstyle object instances - * @paramKey the * @return - */ - Public Statichairinterface Newclass (String key) { -Hairinterface hair =NULL; + Switch(key) { - Case"Right": +Hair =NewRighthair (); A Break; at Case"Left": -Hair =NewLefthair (); - Break; - default: - Break; - in } - returnhair; to } + -}
Test class:
1 /*2 * Created by: Ouyangshengduo3 * Date of creation: March 31, 20174 * File name: Client.java5 * Copyright information: Edan. All rights reserved. 6 * File Description: Test class7 */8 Packagecom.oysd.model.factory;9 Ten Public classClient { One A Public Static voidMain (string[] args) { - //TODO auto-generated Method Stub - theHairinterface hair = Hairfactory.newclass ("Right"); - - Hair.draw (); - + } - +}
Factory mode of Android design mode